Why 1st iteration data is getting replaced in 2nd iteration?
Is there any other simpler method in ES6 to achieve this?
a = [
{ name: 'NameOne', weekName: 'WeekOne' },
{ name: 'NameTwo', weekName: 'WeekTwo' },
];
b = [
{ id: 'Name', type: 'text', data: '' },
{ id: 'Week', type: 'text', data: '' },
];
c = [];
showOutput() {
this.a.forEach((element) => {
this.b.map((item) => {
if (item.id == 'Name') {
item.data = element.name;
}
if (item.id == 'Week') {
item.data = element.weekName;
}
this.c.push(item);
console.log('c', this.c);
});
});
}
Current Output :
[{ id: 'Name', type: 'text', data: 'NameTwo' },
{ id: 'Week', type: 'text', data: 'WeekTwo' },
{ id: 'Name', type: 'text', data: 'NameTwo' },
{ id: 'Week', type: 'text', data: 'WeekTwo' }]
Desired Output:
[{ id: 'Name', type: 'text', data: 'NameOne' },
{ id: 'Week', type: 'text', data: 'WeekOne' },
{ id: 'Name', type: 'text', data: 'NameTwo' },
{ id: 'Week', type: 'text', data: 'WeekTwo' }]
CodePudding user response:
Problem with your code is that this.c.push(item);
here the same object is getting referenced so in 2nd iteration it's changing the data that modified by 1st iteration. In order to solve this, you will have to clone the object (dereference somehow)
I have used c.push(Object.assign({}, item));
or you can use c.push(JSON.parse(JSON.stringify(item)));
or any other way to clone the object before pushing into array (c in your case)
Note: This is just to point out the root cause of the issue, and it may not be the perfect solution for your scenario.
e.g.
a = [
{ name: 'NameOne', weekName: 'WeekOne' },
{ name: 'NameTwo', weekName: 'WeekTwo' },
];
b = [
{ id: 'Name', type: 'text', data: '' },
{ id: 'Week', type: 'text', data: '' },
];
c = [];
function showOutput() {
a.forEach((element) => {
b.map((item) => {
if (item.id == 'Name') {
item.data = element.name;
}
if (item.id == 'Week') {
item.data = element.weekName;
}
c.push(Object.assign({}, item)); // clone object
});
});
}
showOutput();
console.log('c', c);
For more information: https://javascript.info/object-copy