1

This question is related to this other question.

I'm sorry but I can't find the solution. I need to group an array of objects given by dataObject in this fiddle by the property objetivo with the properties: id, indicadores, objetivo and perspetiva.

This is my code:

var res = dataObject.reduce(function(res, currentValue) {
    if ( res.indexOf(currentValue.objetivo) === -1 ) {
      res.push(currentValue.objetivo);
    }
    return res;
}, []).map(function(objetivo) {
    return {
        objetivo: objetivo,
        indicadores: dataObject.filter(function(_el) {
          return _el.objetivo === objetivo;
        }).map(function(_el) { return _el.indicador; }),
        perspetiva: dataObject.perspetiva, 
        id: dataObject.id
    }
});

console.log(res);

Which is grouping by objetivo correctly, but returning undefined for perspetiva and id.

Thanks for helping and sorry if this is duplicating other questions.

Community
  • 1
  • 1
  • 1
    `dataObject` is an array and has neither a `perpetiva` property nor an `id` property. It would be easier if you included example input and output data in the question. – 1983 Jul 31 '15 at 15:39
  • That's right, I need to filter the array and return the property 'perspetiva' and 'id' for those objects containg the 'objetivo' I'm looking for.. –  Jul 31 '15 at 16:04

1 Answers1

0

You're trying to access dataObject.id and .perspetiva, but dataObject is your main array and doesn't have those fields.

After reduce has picked out the unique objetivas, go back and find the items they came from:

.map(function(objetivo) {
    var items = dataObject.filter(function(_el) {
        return _el.objetivo === objetivo;
    });

Then you can find all the indicadors, and since it looks like id and perspetiva are consistent for items with the same objetiva, you can just pick from the first one.

    return {
        objetivo: objetivo,
        indicadores: items.map(function(_el) { return _el.indicador; }),
        perspetiva: items[0].perspetiva,
        id: items[0].id
    }

Here's a working fiddle.

Kristján
  • 18,165
  • 5
  • 50
  • 62
  • Exactly! I was trying to reach the object properties in the array which doesn't make sense. –  Jul 31 '15 at 15:44
  • I just noticed now that the proposed solution isn't grouping by the property 'objetivo'. See res[0] and res[3] and you'll see they're duplicated. The resulting array should have only 11 elements and it contains 19. –  Jul 31 '15 at 15:57