4

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.

0

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

6 Comments

@PiushShukla You are welcome. Better to read some documentation about all the array methods specifically iteration methods before making projects. This will help you alot. You can get a list here developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
One more question how to apply filter if we need to change value based on a condition.
this.state.formOrderItems.map(x => (x.id === ev ? { ...x, isDefault: checked } : x
@PiushShukla What is problem in the above approach?
Nothing , but one of condition i need to filter data based on condition .
|
0

If you don't want to create a new array but instead modify the arr itself then you can use forEach like this:

let arr = [
    { name:"string 1", value:"value1", other: "other1" },
    { name:"string 2", value:"value2", other: "other2" }
    ];
    
    arr.forEach((element) => {
    	element.name = 'new name';
    	element.value = 'new value';
    	element.other = 'that';
    })
    console.log(arr);

Comments