Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class array property value change using find method for all the elements in typescript [duplicate]

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.


1 Answers

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)
like image 169
Maheer Ali Avatar answered Oct 26 '25 22:10

Maheer Ali