I am working with a json object that contains three fields: numbers, name, and type. However, not every name has a type associated with it. Here is an example of 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}
]
In order to process this data effectively, I need each type array to have the following structure:
finalNames = [object1, object2, object3, object4];
resultType1Array = [type1NumbersObject1, type1NumbersObject2, type1NumbersObject3, type1NumbersObject4];
resultType2Array = [type2NumbersObject1, type2NumbersObject2, type2NumbersObject3, type2NumbersObject4];
//and so on
The issue arises when an object does not have all four types present. In such cases, I want to insert a zero in the corresponding position within the arrays. For instance:
resultType1Array = [10, 0, 0, 2]
resultType2Array = [2, 12, 0, 4]
resultType3Array = [15, 0, 1, 3]
resultType4Array = [16, 10, 0, 1234]
However, I am facing challenges in implementing this solution as I cannot seem to correctly insert zeros. My current code produces incorrect values. How can I rectify this problem? Here is a snippet of 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 outcome I currently receive varies depending on the presence or absence of a particular type in the object, resulting in arrays with different lengths. Here is what I get:
resultType1Array = [10, 2]
resultType2Array = [2, 12, 4]
resultType3Array = [15, 1, 3]
resultType4Array = [16, 10, 1234]
How can I accurately place zeros in the appropriate positions within the resultArray for names that lack specific types? Thank you