0

I am trying to add a property (score) to my units array. Scores is an array of object that contains a common id with units.

 this.units.map(unit => {
              unit.score = scores
              .filter(score => unit.id === score.unit_id);
 });

The objects that are contained in the array.

 scores
    {
      unit_id: 1234,
      score: 12,
    }


 this.units
  [
    {
      id: 1234,
      type: 'maths',

    }
   {
      id: '5678',
      type: 'maths',

    }
  ]

It looks ok. Is it because unit.id is not available in the filter?

1
  • Now you have edited the code in your question so it works, so what is the question? Commented Aug 24, 2018 at 10:32

1 Answer 1

2

I think this is what you are after. Score does not have a unit_id property, only id.

var scores = [{
  unit_id: 1234,
  score: 12,
}];
var units = [{
  id: 1234,
  type: 'maths',
}, {
  id: 5678,
  type: 'maths',
}];

units.map(unit => {
  unit.score = scores
    .filter(score => unit.id === score.unit_id);
});

console.log(units);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I was almost there I think I just went round in circles a bit.
You shouldn't be using .map for this, because it doesn't return any value. Use .forEach instead.

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.