skip to Main Content

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]);
}

3

Answers


  1. 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);
    Login or Signup to reply.
  2. You can use higher order function in JavaScript, forEach

    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.forEach((item) => { item.Standard = "Sixth" }) 
    console.log(arr)
    
    Login or Signup to reply.
  3. Refactor your setup to use a getter MDN. If this is coming from JSON you may need to do an iteration once during object creation to modify the getter.

    var arr = [];
    
    var currentStandard = 'Fifth';
    
    var obj1 = {name: 'Alice',get Standard(){return currentStandard}};
    var obj2 = {name: 'Bob',get Standard(){return currentStandard}};
    var obj3 = {name: 'Carl',get Standard(){return currentStandard}};
    
    arr.push(obj1, obj2, obj3);
    
    console.log(arr);
    
    currentStandard = 'Sixth';
    
    console.log(arr);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search