0

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?

2
  • 1
    What have you tried so far? Commented Apr 30, 2018 at 18:15
  • 2
    What @Tschallacka asked. Please show code you've tried so far. Commented Apr 30, 2018 at 18:15

1 Answer 1

2

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;
}, {})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.