I have a sample code below
let arr = [
{ name:"string 1", value:"value1", other: "other1" },
{ name:"string 2", value:"value2", other: "other2" }
];
let obj = arr.find((o, i) => {
arr[i] = { name: 'new name', value: 'new value', other: 'that' };
return true; // stop searching
});
console.log(arr);
I want to replace all the array value with name " new name " and value "new value" , right now it is changing only first array index value.
find() returns the first element of the array which matches the condition. You are returning true from your function so it stops iterating after the first index.
When you have to change each value of array to new value. You should use map(). return and object from the map() function. First copy all the property of the object into the final object using spread oeprator ... then set the desired properties to new values
let arr = [
{ name:"string 1", value:"value1", other: "other1" },
{ name:"string 2", value:"value2", other: "other2" }
];
const res = arr.map(x => ({...x, name: "new name", value: "new value"}))
console.log(res)
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