Techie Techie - 2 months ago 26
Javascript Question

How to create multidimensional array in angular2 with object data?

I have object array, but i want to create its array:
Object format as:

[
{"name":"A1","type":"type1"},
{"name":"A2","type":"type1"},
{"name":"A3","type":"type1"},
{"name":"A4","type":"type1"},
{"name":"B1","type":"type2"},
{"name":"C1","type":"type3"},
{"name":"D1","type":"type4"},
{"name":"D2","type":"type4"}


]

Result Format as :

["type1"=>[A1,A2,A3,A4],"type2"=>[B1],"type3"=>[C1],"type3"=>[D1,D2]]

Answer

You could iterate the array with Array#forEach and use an object with the type as keys.

var data = [{ "name": "A1", "type": "type1" }, { "name": "A2", "type": "type1" }, { "name": "A3", "type": "type1" }, { "name": "A4", "type": "type1" }, { "name": "B1", "type": "type2" }, { "name": "C1", "type": "type3" }, { "name": "D1", "type": "type4" }, { "name": "D2", "type": "type4" }],
    grouped = {};

data.forEach(function (a) {
    grouped[a.type] = grouped[a.type] || [];
    grouped[a.type].push(a.name);
});

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments