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.

2 Answers2

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)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • @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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array – Maheer Ali Feb 27 '20 at 07:13
  • One more question how to apply filter if we need to change value based on a condition. –  Feb 27 '20 at 07:26
  • this.state.formOrderItems.map(x => (x.id === ev ? { ...x, isDefault: checked } : x –  Feb 27 '20 at 07:49
  • @PiushShukla What is problem in the above approach? – Maheer Ali Feb 27 '20 at 07:51
  • Nothing , but one of condition i need to filter data based on condition . –  Feb 27 '20 at 07:54
  • @PiushShukla You need to use `Array.prototype.filter` – Maheer Ali Feb 27 '20 at 13:03
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);
Ramesh Reddy
  • 10,159
  • 3
  • 17
  • 32