admin管理员组文章数量:1202004
I have an array, that holds a large number of two-dimensional arrays:
var myArray = [
[2260146,2334221,"copy"],
[1226218,2334231,"copy"],
[2230932,-1,"copy"],
[2230933,-1,"copy"],
[2230934,-1,"copy"]
]
I need to convert this array into an object of the following form to send it as JSON:
var json = [
{
"s_id": 2260146,
"t_id": 2334221,
"type": "copy"
},
{
"s_id": 1226218,
"t_id": 2334231,
"type": "copy"
},
{
"s_id": 12,
"t_id": -1,
"type": "copy"
}
]
("s_id" should be myArray[0][0]
, "t_id myArray[0][1]
, and "type" myArray[0][2]
and so on.)
How can I get the array in the desired form? Thanks in advance.
I have an array, that holds a large number of two-dimensional arrays:
var myArray = [
[2260146,2334221,"copy"],
[1226218,2334231,"copy"],
[2230932,-1,"copy"],
[2230933,-1,"copy"],
[2230934,-1,"copy"]
]
I need to convert this array into an object of the following form to send it as JSON:
var json = [
{
"s_id": 2260146,
"t_id": 2334221,
"type": "copy"
},
{
"s_id": 1226218,
"t_id": 2334231,
"type": "copy"
},
{
"s_id": 12,
"t_id": -1,
"type": "copy"
}
]
("s_id" should be myArray[0][0]
, "t_id myArray[0][1]
, and "type" myArray[0][2]
and so on.)
How can I get the array in the desired form? Thanks in advance.
Share Improve this question asked Jan 18, 2013 at 11:24 mazemaze 2,2849 gold badges26 silver badges30 bronze badges 1- what have you tried? I'd say just iterate over the array and make the array of objects by hand. – Manuel Commented Jan 18, 2013 at 11:26
4 Answers
Reset to default 14json = myArray.map(function(x) {
return {
"s_id": x[0],
"t_id": x[1],
"type": x[2]
}
})
Be aware that map is not supported in IEs < 9.
You could destructure the parameter in map
and use Shorthand property names:
const myArray=[[2260146,2334221,"copy"],[1226218,2334231,"copy"],[2230932,-1,"copy"],[2230933,-1,"copy"],[2230934,-1,"copy"]]
const output = myArray.map(([s_id, t_id, type]) => ({ s_id, t_id, type }))
console.log(output)
Try with:
var length = myArray.length,
json = [];
for ( var i = 0; i < length; i++ ) {
var subArray = myArray[i],
item = {
s_id: subArray[0],
t_id: subArray[1],
type: subArray[2]
};
json.push(item);
}
How to traverse through the following structure from 2D array
weekearn,monthearn is variable containing array of objects. I need loop because I don't know the number of products
const stackdata = {
datasets:[{
data: weekearn,
label: 'Product 1',
backgroundColor: 'rgb(255, 87, 51)',
borderColor: 'rgb(255, 99, 132)',
},
{
data: monthearn,
label: 'Product 2',
backgroundColor: 'rgb(155, 87, 51)',
borderColor: 'rgb(255, 99, 32)',
}
]
};
本文标签: 2dimensional array to object (JavaScript)Stack Overflow
版权声明:本文标题:2-dimensional array to object (JavaScript) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738618434a2103047.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论