[英]How can we modify javascript array to array object?
我有這個數組arr = [{id:1},{id:2},{id:3},{id:5},{id:5}]
我想修改數組,比如索引 0 - 1 是第一個, 2 -3 是第二個,4 - 5 是第三個,依此類推
結果數組: [first:[{id:1},{id:2}],second:[{id:3},{id:5}],third:[{id:5}]]
如何修改這種類型的數組?
您期望的結果不是有效的數組。
[first: [{},{}]]
它應該是這樣的數組
[[{},{}],[{},{}]]
或 object
{"first":[{},{}],"second":[{},{}]}
下面的代碼將您的輸入轉換為數組,如果您正在尋找一些小的修改,它可以很容易地修改為 object。
const arr = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 5 }, { id: 5 }];
let result = arr.reduce((acc, current, index) => {
if (index % 2 == 0) {
acc.push([current]);
} else {
acc[Math.floor(index / 2)].push(current);
}
return acc;
}, []);
您可以使用array.prototype.map
。 此示例返回每個的 id 值乘以它在數組中存在的數字。
let arr = [{id:1},{id:2},{id:3},{id:5},{id:5}];
arr.map(function(item,index) {
return item.id * index;
})
試試看!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.