Let's say I have an array in the form:
const array = [{id: 1, title: "this"}, {id: 2, title: "that"}];
I would like to change the value of one element in a given object. So that, for example, my output is like so:
[{id: 1, title: "this"}, {id: 2, title: "foo foo foo"}];
I'm passing an object with two properties to my function. The first property is the id of the object I'd like to modify, and the second property is the new title:
[2, "foo foo foo"]
I'm able to find the index of the correct object using the following code:
index = array.findIndex(item => item.id === arr[0]);
But I can't figure out how to change the element and replace it with my new title (arr[1]).
I would like to change the title element in the second object without mutating the array. Any advice is greatly appreciated.
EDIT: Sorry for the confusion regarding "without mutating the array". What I meant was I don't want the returned array to be simply a mutation of the original array, but rather a new array. Maybe "without mutating the state" would have been a better choice of words.
For example, if I were to return the an array like so: return [...state] That would give me a new array (albeit with no changes) without mutating the original array.
You can't really change an object without … well mutating it. You need a copy of the object. Assuming it's not going to cost to much to copy the array, you can do something like:
const arr = [{id: 1, title: "this"}, {id: 2, title: "that"}];
const a2 = arr.map(i => i.id == 2 ? Object.assign({}, i, {title: 'foo foo foo'}): i)
console.log("original: ", arr)
console.log("with changes: ", a2)
In this case, you are copying the original objects with the exception of the changed one, which gets a copy with the changes and leaves the original alone.
You can make use of Array.map function to iterate over the array and return the new array. In map function, check if the id is same as the id passed in the arguments of the function. If the condition is true, create a new object using ...(spread operators).
const arr = [{id: 1, title: "this"}, {id: 2, title: "that"}];
var change = (id, title) => {
return arr.map(obj => {
if (obj.id === id) {
return {...obj, title};
}
return obj;
});
}
var arr2 = change(2, "foo foo foo");
console.log("original: ", arr);
console.log("with changes: ", arr2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With