FacundoGFlores
FacundoGFlores

Reputation: 8118

Adding property using Object assign

I have the following function:

addHrefs = (list) => {
    const listWithHrefs = list.map((item) => {
        item.href = customFunction(item.name);
        return item;
    });
    return listWithHrefs;
}

The problem here is I am mutating the list object. I want to know how to add a particular (key, value) pair without mutating list. Is it possible with Object.assign? How can I do it?

Upvotes: 5

Views: 8659

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386578

It is possible with Object.assign.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

You could assign the property value to a new object and return it.

addHrefs = list =>
    list.map(item => Object.assign({}, item, { href: customFunction(item.name) }));

Upvotes: 6

guest271314
guest271314

Reputation: 1

You can pass plain object as first parameter to Object.assign(), referenced object at second parameter. Perform action on variable assigned to Object.assign(), return variable

let list = [{
  a: 1
}, {
  a: 2
}, {
  a: 3
}];

let res = list.map(item => {
  let o = Object.assign({}, item);
  // do stuff with `o`
  o.a = o.a + 10;
  // return `o`
  return o
});

console.log(list, res);

Upvotes: 1

Related Questions