0

I have an array of objects, each of these objects have a capability attribute, there are 4 different types, I want to split the array into 4 different arrays based on what their capability value is.

Tried to map but couldnt work out how to do it based on one of their values.

ngOnInit(){
    this.questionsService.getQuestions().subscribe(
        data => {
            this.questions = [];
            Object.keys(data).map((key)=>{ this.questions.push(data[key])});
            console.log(this.questions);
        }
    );
}

Examples of the objects:

{
    "Capability": "Associate",
    "SubCategory": "Core Skills",
    "Skill": "Communication",
    "SkillID": 1
},
{
    "Capability": "CCM",
    "SubCategory": "Other Skills",
    "Skill": "Data Protection/ GDPR",
    "SkillID": 34
}

I want the array of questions to be split into four different arrays, an array each for the different values of capability.

Iñigo
  • 1,877
  • 7
  • 25
  • 55
Luke Harland
  • 33
  • 1
  • 7

1 Answers1

0

I think your issue is same with here How to group an array of objects by key

var myArray = [
{ capability: 1, id: 1},
{ capability: 1, id: 2},
{ capability: 2, id: 3},
{ capability: 3, id: 4},
{ capability: 4, id: 5}
]
var result = myArray.reduce(function (r, a) {
r[a.capability] = r[a.capability] || [];
r[a.capability].push(a);
return r;
}, Object.create(null));

console.log(result);