我想将 JSON 对象解析为二维数组。但我的代码不起作用。下面是我的例子:{\'test\':[ { \'id\': 1, \'first_name\': \'Robert\'...
我想将 JSON 对象解析为二维数组。但我的代码不起作用。这是我的示例:
{
"test":[
{
"id": 1,
"first_name": "Robert",
"last_name": "Schwartz",
"email": "[email protected]"
},
{
"id": 2,
"first_name": "Lucy",
"last_name": "Ballmer",
"email": "[email protected]"
},
{
"id": 3,
"first_name": "Anna",
"last_name": "Smith",
"email": "[email protected]"
}
]
};
var as = JSON.parse(test);
console.log(as)
我以为我可以使用解析函数来解析规范化数组。但是它不起作用。
结果数组应该是这样的:
[[1,"Robert","Schwartz","[email protected]"],[2,"Lucy","Ballmer","[email protected]"],[3,"Anna","Smith", "[email protected]"]]
感谢您提供所有解决方案。
使用 ES 6 实现 @zer00ne 答案
const data = [{
"id": 1,
"first": "Robert",
"last": "Schwartz",
"email": "[email protected]"
},
{
"id": 2,
"first": "Lucy",
"last": "Ballmer",
"email": "[email protected]"
},
{
"id": 3,
"first": "Anna",
"last": "Smith",
"email": "[email protected]"
}
];
const convert = arrOfObj => {
const keyArr = Object.keys(arrOfObj[0]);
return arrOfObj.map(obj => keyArr.map(key => obj[key]));
};
console.log(convert(data));