Home > database >  How to Update multiple Values in Array of object without Iteration in Javascript
How to Update multiple Values in Array of object without Iteration in Javascript

Time:01-18

I have an array of objects. Is it possible to update the value of Standard From "Fifth" to "Sixth" (in One Go) without any Iteration? We can iterate the Array and modify the value as shown below. Is there any better approach than this?
This is my Pseudo Example, in real time I have to modify values for more than 2000 rows in an array and I have more than 100 arrays and Iterating 100 of 2000 rows takes time.

At least I need without FOR iteration.

Thanks in Advance!!!

var arr = [];

var obj1 = {name: 'Alice',Standard:'Fifth'};
var obj2 = {name: 'Bob',Standard:'Fifth'};
var obj3 = {name: 'Carl',Standard:'Fifth'};

arr.push(obj1, obj2, obj3);

for (var j = 0; j < arr.length; j  )
{
    arr[j].Standard="Sixth";
    console.log(arr[j]);
}

CodePudding user response:

You can't go through all the objects in the array without iterating, but you can use array methods, like .map() if you want to return a new array or .forEach if you want to change an existing one instead of simple for, this is examples of each one:

To return new array (This example only copies the first layer of the object, it will work for objects without nesting):

newArr = arr.map(obj => {
  copy = {...obj}
  copy.Standard = 'Sixth'
  return copy
})

To change an existing one:

arr.forEach(obj => {
      obj.Standard = 'Sixth'
    })

CodePudding user response:

You can use the map function

var arr = [];

var obj1 = {name: 'Alice',Standard:'Fifth'};
var obj2 = {name: 'Bob',Standard:'Fifth'};
var obj3 = {name: 'Carl',Standard:'Fifth'};

arr.push(obj1, obj2, obj3);

arr.map(x => x.Standard="Sixth");
console.log(arr);

  • Related