我有对象
let obj1 = { categoryId:1, category:"Fruits", name:"Orange"}
let obj2 = { categoryId:1, category:"Fruits",name:"Apple"}
let obj3 = { categoryId:2, category:"Vegetables", name:"Onion"}
let obj4 = { categoryId:2, category:"Vegetables", name:"Ginger"}....etc
我想根据这个数组创建一个 map :
{
"Fruits": [{
"categoryId": 1,
"category": "Fruits",
"name": "Orange"
}, {
"categoryId": 1,
"category": "Fruits",
"name": "Apple"
}],
"Vegetables": [{
"categoryId": 2,
"category": "Vegetables",
"name": "Onion"
}, {
"categoryId": 2,
"category": "Vegetables",
"name": "Ginger"
}]
}
我正在寻找一个功能来逐一添加到 map
addtoMap( obj1);
addtoMap( obj2);
addtoMap( obj3);
addtoMap( obj4);....etc
同时从 map 中删除
removeFromMap( obj1);
我已经尝试过
addtoMap(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
最佳答案
您可以检查该对象是否存在并将该对象添加到所需的类别中。删除对象也是如此,直到组中不再有对象为止。然后该组也会被删除。
function addToCollection(collection, object) {
if (!collection[object.category]) {
collection[object.category] = [object];
return;
}
if (collection[object.category].includes(object)) return;
collection[object.category].push(object);
}
function removeFromCollection(collection, object) {
if (!collection[object.category]) return;
var index = collection[object.category].indexOf(object);
if (index === -1) return;
collection[object.category].splice(index, 1);
if (!collection[object.category].length) delete collection[object.category];
}
var obj1 = { categoryId: 1, category: "Fruits", name:"Orange" },
obj2 = { categoryId: 1, category: "Fruits", name:"Apple" },
obj3 = { categoryId: 2, category: "Vegetables", name:"Onion" },
obj4 = { categoryId: 2, category: "Vegetables", name:"Ginger" },
collection = {};
addToCollection(collection, obj1);
addToCollection(collection, obj2);
addToCollection(collection, obj3);
addToCollection(collection, obj4);
console.log(collection);
removeFromCollection(collection, obj2);
console.log(collection);
removeFromCollection(collection, obj1);
console.log(collection);
关于javascript - 从元素创建 map 对象 JavaScript 添加或删除值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56108317/