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?
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 => Objects.assign({}, item, { href: customFunction(item.name) }));
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` oa = oa + 10; // return `o` return o }); console.log(list, res);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.