我有一个像这样的对象:
const arr = {
[1]: [{id: 1, category: 1}, {id: 2, category: 2}],
[2]: [{id: 3, category: 2}, {id: 4, category: 2}],
[3]: [{id: 5, category: 3}, {id: 6, category: 3}]
}
是否可以将{id:2,category:2}移动到另一个地方:
const arr = {
[1]: [{id: 1, category: 1}],
[2]: [{id: 2, category: 2}, {id: 3, category: 2}, {id: 4, category: 2}],
[3]: [{id: 5, category: 3}, {id: 6, category: 3}]
}
category = 2的项目应该在数组[2],3 in 3等等中。可以用Object.keys和过滤器进行操作吗?或者可能有更好的解决方案?
答案 0 :(得分:1)
是的,Object.keys可用于遍历数组。然后,使用Array.splice和Array.push,您可以删除项目并将其推送到正确的位置。请检查以下代码:
const arr = {
[1]: [{id: 1, category: 1}, {id: 2, category: 2}, {id: 7, category: 3}],
[2]: [{id: 3, category: 2}, {id: 4, category: 2}],
[3]: [{id: 5, category: 3}, {id: 6, category: 3}]
};
Object.keys(arr).forEach(function(k){
for(var j = 0; j < arr[k].length;j++) {
if(arr[k][j].category!=k) {
var removedItem = arr[k].splice(arr[k].indexOf(j), 1);
var pushedArr = arr[removedItem[0].category];
if(pushedArr) {
pushedArr.push(removedItem[0]);
j--;
}
}
}
});
console.log(arr);
&#13;
答案 1 :(得分:1)
您可以使用Object.keys()
遍历arr
,然后使用array#reduce
,您可以将数组分组到category
值。
const arr = {[1]: [{id: 1, category: 1}, {id: 2, category: 2}], [2]: [{id: 3, category: 2}, {id: 4, category: 2}], [3]: [{id: 5, category: 3}, {id: 6, category: 3}]},
result = Object.keys(arr).reduce((r,k) => {
arr[k].forEach(({id, category}) => {
r[category] = r[category] || [];
r[category].push({id, category});
})
return r;
},{});
console.log(result);
您可以使用array#concat
对象的所有值,然后使用基于array#reduce
的{{1}}组对象。
category