[英]JavaScript convert Array of Array of Objects into Array of objects
我需要使用JavaScript將對象數組轉換為簡單對象數組
我在下面放當前代碼和當前輸出
const result = [
[
{
name: '1'
},
{
name: '2'
}
],
[
{
name: '3'
},
{
name: '4'
}
],
[
{
name: '5'
}
],
[
{
name: '6'
}
]
]
const a = result.map(item => {
return Object.assign({}, ...item)
})
console.log(a)
上面代碼的輸出(當前和錯誤輸出)
[ { "name": "2" }, { "name": "4" }, { "name": "5" }, { "name": "6" } ]
預期和需要的產出
[
{
name: '1'
},
{
name: '2'
},
{
name: '3'
},
{
name: '4'
},
{
name: '5'
},
{
name: '6'
}
]
有一個簡單,支持全面的方式扁平化陣列,而不使用flat
-使用reduce
和push
(不concat
效率)。
const result = [ [ { name: '1' }, { name: '2' } ], [ { name: '3' }, { name: '4' } ], [ { name: '5' } ], [ { name: '6' } ] ] const a = result.reduce((acc, curr) => (acc.push(...curr), acc)); console.log(a);
.as-console-wrapper { max-height: 100% !important; top: auto; }
ES5語法:
var result = [ [ { name: '1' }, { name: '2' } ], [ { name: '3' }, { name: '4' } ], [ { name: '5' } ], [ { name: '6' } ] ] var a = result.reduce(function(acc, curr) { return (Array.prototype.push.apply(acc, curr), acc); }); console.log(a);
您可以使用Array.prototype.concat合並數組。
const result = [ [ { name: '1' }, { name: '2' } ], [ { name: '3' }, { name: '4' } ], [ { name: '5' } ], [ { name: '6' } ] ] const b = Array.prototype.concat.apply([], result); console.log(b);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.