如何在对象数组中为对象动态添加额外属性?
如何为数组对象动态添加对应分类的counter属性?
嘿,这需求很常见,我来给你两种实用的解决办法,根据你的场景选就行!
先把你的原始数据贴出来方便对照:
let items = [ {name: 'Carlsberg', category: 'Beer', price: '4.99'}, {name: 'Smirnoff', category: 'Vodka', price: '28.99'}, {name: 'Miller Lite', category: 'Beer', price: '7.99'} ]; const categories = { beerCounter:2, vodkaCounter:1 };
方法1:用map生成新数组(推荐,不改动原数据)
这种方法会返回一个全新的数组,原数组保持不变,非常适合需要保留原始数据的场景:
const updatedItems = items.map(item => { // 把分类名转成小写,拼接成categories里对应的键名 const counterKey = `${item.category.toLowerCase()}Counter`; // 合并原对象属性和新的counter属性 return { ...item, counter: categories[counterKey] }; }); // 输出结果就是你想要的格式啦 console.log(updatedItems);
方法2:用forEach直接修改原数组
如果你不需要保留原数组,想直接在原数组上修改,可以用forEach:
items.forEach(item => { const counterKey = `${item.category.toLowerCase()}Counter`; item.counter = categories[counterKey]; }); console.log(items);
小说明
两种方法的核心都是根据item的category匹配categories里对应的键:把Beer转成beer,再拼接Counter得到beerCounter,然后通过方括号categories[counterKey]拿到对应的值,最后添加为新属性。
内容的提问来源于stack exchange,提问作者Jan Tuđan
相关产品推荐
相关产品推荐

