[英]Converting array of json objects to 2-D array
I have array of JSON objects as follows: 我有JSON对象数组,如下所示:
var out = [{
1: {
name: 'Name 1',
id: 'one'
}
}, {
2: {
name: 'Name 2',
id: 'two'
}
}];
I am trying to convert this to 2-D array as: 我试图将其转换为2-D数组为:
var out = [[1,object],[2,object]];
I tried to use json.encode(out) , any methods or approaches for converting this? 我尝试使用json.encode(out),有什么方法或方法可以转换此格式?
simply try 只需尝试
var output = out.map(function(val){
var keyName = parseInt(Object.keys(val)[0],10);
var value = val[keyName];
return [keyName, value];
});
DEMO 演示
var out = [{ 1: { name: 'Name 1', id: 'one' } }, { 2: { name: 'Name 2', id: 'two' } }]; var output = out.map(function(val) { var keyName = parseInt(Object.keys(val)[0],10); var value = val[keyName]; return [keyName, value]; }); document.body.innerHTML += JSON.stringify(output,0,4);
You can use map()
and Object.keys()
您可以使用
map()
和Object.keys()
var out = [{ 1: { name: 'Name 1', id: 'one' } }, { 2: { name: 'Name 2', id: 'two' } }]; var res = out.map(function(v) { var key = Object.keys(v)[0]; return [parseInt(key,10), v[key]]; }) document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');
A proposal for a more dynamic data structure, without stress to the first key 提出一种更加动态的数据结构,而无需强调第一个关键的提议
var out = [{ 1: { name: 'Name 1', id: 'one' } }, { 2: { name: 'Name 2', id: 'two' } }], result = []; out.forEach(function (a) { Object.keys(a).forEach(function (k) { result.push([+k, a[k]]); }); }); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
To meet your requirement: ( [[1,object],[2,object]]
) "1"
and "2"
keys should be numbers : 为了满足您的要求:(
[[1,object],[2,object]]
) "1"
和"2"
键应为数字 :
var result = out.map(function(v){
var k = Object.keys(v)[0];
return [parseInt(k),v[k]];
});
console.log(JSON.stringify(result,0,4));
The console.log output: console.log输出:
[
[
1,
{
"name": "Name 1",
"id": "one"
}
],
[
2,
{
"name": "Name 2",
"id": "two"
}
]
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.