Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
66
rated 0 times [  68] [ 2]  / answers: 1 / hits: 5291  / 4 Years ago, thu, february 27, 2020, 12:00:00

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.


More From » typescript

 Answers
3

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)




[#4622] Sunday, February 23, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shylaelisan

Total Points: 37
Total Questions: 94
Total Answers: 110

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
;