Looking to frame an object as a two-dimensional entity.
let data = [
{'id':1, 'price':'12', 'price_type':'abc', 'mode':1, 'year':1},
{'id':1, 'price':'22', 'price_type':'def', 'mode':1, 'year':1},
{'id':1, 'price':'15', 'price_type':'abc', 'mode':1, 'year':2},
{'id':1, 'price':'32', 'price_type':'def', 'mode':1, 'year':2},
{'id':1, 'price':'30', 'price_type':'abc', 'mode':1, 'year':3},
{'id':1, 'price':'35', 'price_type':'def', 'mode':1, 'year':3}
];
The desired output is:
{mode:{year:{'abc_price':price1, def_price:price2}}
For example:
results = {
1:{
1:{'abc_price':12, def_price:22},
2:{'abc_price':15, def_price:32},
3:{'abc_price':30, def_price:35}
}
}
How can I achieve the above result with the provided object? Your assistance is greatly appreciated.
I attempted the following approach:
let tmpArr = [];
let objArr = {};
for(let i = 0; i < data.length; i++) {
objArr[data[i].mode][data[i].year] = {'mode': data[i].mode, 'year': data[i].year};
if(data[i].price_type == "abc") {
objArr[data[i].mode][data[i].year]['abc_price'] = data[i].price;
}
if(data[i].price_type == "def") {
objArr[data[i].mode][data[i].year]['def_price'] = data[i].price;
}
tmpArr.push(objArr);
}
console.log("temp Array: "+ JSON.stringify(tmpArr));
An error was encountered due to an undefined index value in a two-dimensional array.