我有一个对象数组和两个对象
像这样的对象数组
[ { id: 1, name: 'Monthly Plan', cycle: 1, fees: 1000 },
{ id: 2, name: 'Yearly Plan', cycle: 12, fees: 10000 },
{ id: 3, name: 'Two Months Plan', cycle: 2, fees: 1500 },
{ id: 4, name: 'Three Months Plan', cycle: 3, fees: 2500 },
{ id: 5, name: 'Four Months Plan', cycle: 4, fees: 3000 }]
现在通过运行像这样的for循环实际上我正在制作这些对象的对象
if (newPlans) {
newPlans.forEach(element => {
let object = {};
object.id = element.id;
object.name = element.name,
object.cycle = element.cycle,
object.fees = element.fees
console.log(object);
console.log(Object.assign(billPlans.filter(bp => bp.id), object))
});
}
我希望得到像这样的结果
[ { id: 1, name: 'Monthly Plan', cycle: 1, fees: 1000 },
{ id: 2, name: 'Yearly Plan', cycle: 12, fees: 10000 },
{ id: 3, name: 'Two Months Plan', cycle: 2, fees: 1500 },
{ id: 4, name: 'Three Months Plan', cycle: 3, fees: 2500 },
{ id: 5, name: 'Four Months Plan', cycle: 4, fees: 3000 },
{ id: 6, name: 'Five Months Plan', cycle: 5, fees: 4000 }
{ id: 7, name: 'Six Months Plan', cycle: 6, fees: 5000 } ]
但是我得到了类似的东西
//console.log(object)
{ id: 6, name: 'Five Months Plan', cycle: 5, fees: 4000 }
//console.log(object.assign)
[ { id: 1, name: 'Monthly Plan', cycle: 1, fees: 1000 },
{ id: 2, name: 'Yearly Plan', cycle: 12, fees: 10000 },
{ id: 3, name: 'Two Months Plan', cycle: 2, fees: 1500 },
{ id: 4, name: 'Three Months Plan', cycle: 3, fees: 2500 },
{ id: 5, name: 'Four Months Plan', cycle: 4, fees: 3000 },
id: 6,
name: 'Five Months Plan',
cycle: 5,
fees: 4000 ]
//console.log(object)
{ id: 109, name: 'Six Months Plan', cycle: 6, fees: 5000 }
//console.log(object.assign)
[ { id: 1, name: 'Monthly Plan', cycle: 1, fees: 1000 },
{ id: 2, name: 'Yearly Plan', cycle: 12, fees: 10000 },
{ id: 3, name: 'Two Months Plan', cycle: 2, fees: 1500 },
{ id: 4, name: 'Three Months Plan', cycle: 3, fees: 2500 },
{ id: 5, name: 'Four Months Plan', cycle: 4, fees: 3000 },
id: 7,
name: 'Six Months Plan',
cycle: 6,
fees: 5000 ]
正如您所看到的,Object.assign
覆盖了之前添加的对象,并且object
的分配方式不正确,因为您可以看到它未以对象方式分配,因此我该如何实现此目的。
答案 0 :(得分:0)
您无需分配,而是将对象推入数组。
如果billPlans
是包含5个元素的上述数组,则只需要执行
let object = {};
object.id = element.id;
object.name = element.name,
object.cycle = element.cycle,
object.fees = element.fees
billPlans.push(object);
此外,我不知道你为什么要过滤数组,但主要的概念是推入数组,而不是使用Object.assign
。
Object.assign
只是将目标中的属性复制到源对象中。
答案 1 :(得分:0)
进一步阐述前面给出的答案,尝试使用更具功能性的方法,不会将数据变异作为副作用。 .forEach()
将运行一个循环,在每个索引处执行给定的函数,但不会保留最初传递的数据。而是根据您的最终目标使用.map()
,.filter()
或.reduce()
。按原样查看您的代码和问题,.map()
工作正常(尽管您可以轻松地将.filter()
/ .reduce()
或更多.map()
方法链接到原始.map()
。.forEach()
无法链接。
const ObjGenerator = (newPlans) =>
!newPlans ? null :
newPlans
.map(el => { ...el }
.map(obj => {
console.log(obj)
return obj
}
.map(obj => {
// rather than using the immutable `.push()` method, try
// the non-immutable alternative via `.concat()`
// Also, dynamic invocation of Object.assign provided.
return Object.assign.apply(billPlans.filter(bp => bp.id), [{}].concat(obj))
}
ObjGenerator(newPlans)
使用我描述的方法还会删除可能创建的任何重复条目。