[英]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.