0

I have the following array of objects:

 [
      {status: 3, name: Joe},
      {status: 3, name: John}, 
      {status: 2, name: Lucas}, 
      {status: 1, name: Jeremiah}, 
      {status: 1, name: Steven}
    ]

I would like to find and replace all objects where status is equal to 1 with the number 2 so that the resulting array would be in the same order:

[
      {status: 3, name: Joe},
      {status: 3, name: John}, 
      {status: 2, name: Lucas}, 
      {status: 2, name: Jeremiah}, 
      {status: 2, name: Steven}
 ]

This array could potentially be any length from 1 to around 10,000 so I would like to find a memory-efficient approach to this scenario.

Any help is well appreciated.

Luis
  • 305
  • 1
  • 14
  • Hi! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. There's no special trick here, just update the property value in a loop. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder May 06 '20 at 17:44
  • do you want to mutate the object or get a new array with new objects? – Nina Scholz May 06 '20 at 18:01
  • @NinaScholz Mutate, I'm trying to update the status value while maintaining every other property the same – Luis May 06 '20 at 18:49

2 Answers2

0

Maybe like this:

var data =[
      {status: 3, name: 'Joe'},
      {status: 3, name: 'John'},
      {status: 2, name: 'Lucas'},
      {status: 1, name: 'Jeremiah'},
      {status: 1, name: 'Steven'}
    ];
 function change_status(_data, _old, _new){
  for(var key in _data){
   if(_data[key].status == _old){
    _data[key].status = _new;
   }
  }
  return _data;
 }

console.log(change_status(data, 1, 2));
mscdeveloper
  • 2,749
  • 1
  • 10
  • 17
  • `for-in` is **not** for looping through arrays. See [my answer here](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript/9329476#9329476) for appropriate ways to loop through an array. – T.J. Crowder May 06 '20 at 17:49
0

Just make a check and an update.

var data = [{ status: 3, name: 'Joe' }, { status: 3, name: 'John' }, { status: 2, name: 'Lucas' }, { status: 1, name: 'Jeremiah' }, { status: 1, name: 'Steven' }];

data.forEach(item => {
    if (item.status === 1) item.status++;
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392