Jim Dover
Jim Dover

Reputation: 623

Changing nested object values

I have a JS object that I am trying to loop through and change values of.

Example of the object below:

var response = { 
'2433345':
[ 
{ 
   taskId: 20295179,
   stageId: 'AB-5R-GF', 
},
{ 
   taskId: 20295176,
   stageId: 'AB-5R-GF',
},
],
'2539643':
[
{ 
   taskId: 28295179,
   stageId: 'AB-5R-RD', 
},
{ 
   taskId: 20445176,
   stageId: 'AB-5R-ZZ',
},
]
}

The parent values are JobIDs, then an array with nested objects for each stage and task within that job.

I am trying to iterate through and change the stageID values to sequential numbers. Each number in a job higher than the last, keeping duplicates the same number.

The desired result would be:

var response = { 
'2433345':
[ 
{ 
   taskId: 20295179,
   stageId: 1, 
},
{ 
   taskId: 20295176,
   stageId: 1,
},
],
 '2539643':
 [
 { 
   taskId: 28295179,
   stageId: 1, 
   },
   { 
   taskId: 20445176,
   stageId: 2,
},
]
}

I am wondering what the best approach would be to solve this? Would using Lodash and _.uniqBy be the best way?

Upvotes: 0

Views: 76

Answers (1)

itamar
itamar

Reputation: 3967

Even though you didn't show your own code - here is my own try. Untested - but here is an explanation. Rebuilding the result, we're starting at {} and for each value's array items, we're writing over the stageItem with an index that increments.

We keep a list on the side to keep track of the index of the items in the array and check whether we're putting a new index in for stageId or an existing one from the list.

var index = 0;
var finalResult = _.reduce(response, function(result, value, key) {
  indexOfIDs = {};
  result[key] = [];
  _.each(value, function(item){
    if(typeof indexOfIds[item.taskId] !== 'undefined'){
       result[key].push(_.assign(item, {stageId: indexOfIds[item.taskId]}))
    } else {
       indexOfIds[item.taskId] = index++;
       result[key].push(_.assign(item, {stageId: index}))
    }

  })
  return result;
}, {})

Upvotes: 2

Related Questions