I have one array of objects and two objects
array of objects something like this
[ { 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 }]
and now comes the objects actually I am making these objects by running a for loop something like this
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))
});
}
and I want to get result something like this
[ { 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 } ]
but I am getting something like this
//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 ]
As you can see the Object.assign
is overriding the previously added object and object
is assigning not in correct way as you can see it is not assigned in the object way so how can I achieve this .
You need not to assign, but push the object into the array.
If the billPlans
is the above array with 5 elements, you need just to do
let object = {};
object.id = element.id;
object.name = element.name,
object.cycle = element.cycle,
object.fees = element.fees
billPlans.push(object);
Also I don't know why you are filtering the array, but the main concept is to push into the array, not use Object.assign
.
Object.assign
just copies the properties from the destinations into the source object.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments