I have a json object that has 3 fields: numbers, name, type, but type is not always present for every name. Here's my object:
myObj=
[{numbers: 10, name: object1, type: type1},
{numbers: 2, name: object1, type: type2}
{numbers: 15, name: object1, type: type3}
{numbers: 16, name: object1, type: type4}
{numbers: 12, name: object2, type: type2}
{numbers: 10, name: object2, type: type4}
{numbers: 1, name: object3, type: type3}
{numbers: 2, name: object4, type: type1}
{numbers: 4, name: object4, type: type2}
{numbers: 3, name: object4, type: type3}
{numbers: 1234, name: object4, type: type4}
]
As you can see no every object has all the types, and the resulting type arrays should have this structure:
finalNames = [object1, object2, object3, object4];
resultType1Array = [type1NumbersObject1, type1NumbersObject2, type1NumbersObject3, type1NumbersObject4];
resultType2Array = [type2NumbersObject1, type2NumbersObject2, type2NumbersObject3, type2NumbersObject4];
//and so on
The problem is that not every object contains all 4 types, and whenever I don't have a type I'd like to add a 0 in the position where it should belong to. So in my case it would be:
resultType1Array = [10, 0, 0, 2]
resultType2Array = [2, 12, 0, 4]
resultType3Array = [15, 0, 1, 3]
resultType4Array = [16, 10, 0, 1234]
but I can't insert 0's and I get arrays with wrong values. How can I achieve this solution? Here's my code:
myObj.forEach(v => names.push(v[Object.keys(v)[1]]));
myObj.forEach(v =>{
if(v.Type === "type1"){
resultType1Array.push(v[Object.keys(v)[0]]);
}
if(v.Type === "type2"){
resultType2Array.push(v[Object.keys(v)[0]]);
}
if(v.Type === "type3"){
resultType3Array.push(v[Object.keys(v)[0]]);
}
if(v.Type === "type4"){
resultType4Array.push(v[Object.keys(v)[0]]);
}
totalNames = [...new Set(names)];
})
The result I get can have a variable number of elements in the array depending on the existence or not of a type in the object. This is my result:
resultType1Array = [10, 2]
resultType2Array = [2, 12, 4]
resultType3Array = [15, 1, 3]
resultType4Array = [16, 10, 1234]
How can I place a 0 in the correct position of the resultArray if the name doesn't have that specific type? Thank you