-1

I have an Array of Objects:

reviewers = [
              {
               id: ''
              },
              {},
              {}
            ]

Each of these objects is homogeneous (with several other keys except the 'id' one). I also have a single Object, with the following structure:

reviewerCounters = {
                     12345678: 3,
                     12312312: 2,
                     14234234: 0
                   }

The idea is that in the second object, I have the value of the property 'id' ( id - value) The length of the object is always the same as the length of the reviewers array.

I need a function that takes the value of each ID on the second object, and outputs that value in the new property 'Counter' in each object of the first array, the ID of which matches the ID of the taken value.

Thus, the ouput would be :

reviewers = [
              {
               id: '12345678',
               counter: '3'
              },
              {},
              {}
            ]

What would be the best way to achieve this?

d0st
  • 127
  • 1
  • 7
  • 1
    Welcome to Stack Overflow! Please take the [tour] and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Do your research, [search](/help/searching) for related topics on SO, and give it a go. What yo've described above isn't difficult, you combine looping with [brackets notation](http://stackoverflow.com/questions/4244896/). ***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. Good luck! – T.J. Crowder Jan 21 '18 at 10:58

2 Answers2

1

You could use a single loop of the array and check if the id exists in the counters object. If it exists, then assign the value.

var reviewers = [{ id: '12345678' }, {}, {}],
    reviewerCounters = { 12345678: 3, 12312312: 2, 14234234: 0 };
    
reviewers.forEach(function (o) {
    if (o.id in reviewerCounters) {
        o.counter = reviewerCounters[o.id];
    }
});

console.log(reviewers);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • as expected, I was over-complicating the problem... Good and tight solution. Thanks! – d0st Jan 21 '18 at 11:49
0

Iterating over an object is quite tricky, combining it with a nested iteration over an array, something like this can help you probably:

function addCounter(obj, arrayData)
{
  var keys = Object.keys(obj);
  for(var i = 0; i < keys.length; i++)
  {
     var id = obj[keys[i]];
     for(var w = 0; w < arrayData.length; w++)
     {
        if(arrayDaya[w]['id'] == id)
        {
           arrayData[w]['counter'] = obj[keys[i]];
        }
     }

    return arrayData;
  }
}
connexo
  • 53,704
  • 14
  • 91
  • 128
Mostafa Talebi
  • 8,825
  • 16
  • 61
  • 105