[英]javascript how to normlize array into the proper format json
我有一个看起来像这样的数组
var arr = [ [{a:1}],
[{b:1}],
[{c:1}],
[{d:1}],
[{e:1}] ]
我想做的是像这样创建一个适当的格式
[{a:1},{b:1},{c:1},{d:1},{e:1}]
尝试了许多来源,但无法找到最佳解决方案
任何人都可以帮忙吗?
这应该对你有用(不理想,但它有效)
var arr = [ [{a:1}],
[{b:1}],
[{c:1}],
[{d:1}],
[{e:1}] ];
//this is not ideal but it works for u
for (var i = 0; i <arr.length - 1; i++) {
arr[i] = arr[i][0];
}
console.log(arr);
简单地
const res = arr.flat()
或者:
const arr = [ [{ a:1 }], [{b: 1}], [{c:1}], [{d:1}], [{e:1}] ] const res = arr.map(([o])=> ({...o})) // for a copy of objects console.log( JSON.stringify( res ))
或:(不创建新数组)
const arr = [ [{ a:1 }], [{b: 1}], [{c:1}], [{d:1}], [{e:1}] ] arr.forEach(([o],i,a)=>a[i]=o) console.log( JSON.stringify( arr ))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.