Reputation: 53
I am trying to create an new array of objects adding a new key and value pair to it. The problem I have is that the addActive function below changes the argument array for some reason. What is even more puzzling is why even if I add var itemList = data;
to the script, it still alters the initial data
array by adding an extra column to it.
Coming from Python background it seems a bit illogical to me, especially when documentation says map
creates a new array. Could someone please explain?
const data = [{ age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
{ age: 21, first_name: 'Larsen', last_name: 'Shaw' },
{ age: 89, first_name: 'Geneva', last_name: 'Wilson' },
{ age: 38, first_name: 'Jami', last_name: 'Carney' }];
function getFields(df) {
return Object.keys(df[0])
}
var itemList = data;
function addActive(df) {
return itemList.map((o) => {
o.isActive = true;
return o;
})
}
const items = addActive(itemList);
const fields = getFields(data);
console.log(fields)
Upvotes: 3
Views: 48
Reputation: 370729
While .map
creates a new array, its arguments are direct references to objects in the old array:
const obj = {};
const arr = [obj];
const newArr = arr.map((item) => {
console.log(item === obj);
});
If you mutate one of these objects and then return it, the items in the old array will be mutated too. The new array will be composed of the same objects as in the old array, despite being a different collection.
If you want to clone the child objects as well, use spread syntax instead:
function addActive(df) {
return itemList.map((o) => ({ ...o, isActive: true }));
}
const data = [{ age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
{ age: 21, first_name: 'Larsen', last_name: 'Shaw' },
{ age: 89, first_name: 'Geneva', last_name: 'Wilson' },
{ age: 38, first_name: 'Jami', last_name: 'Carney' }];
function getFields(df) {
return Object.keys(df[0])
}
var itemList = data;
function addActive(df) {
return itemList.map((o) => ({ ...o, isActive: true }));
}
const items = addActive(itemList);
const fields = getFields(data);
console.log(fields)
This results in the new array items being entirely separate objects from the original array items.
Upvotes: 3