Reputation: 394
I have this object.
{"SI":{"0":"1","1":""},"Description of Goods":{"0":"LTD","1":"TET"},"HSN/SAC":{"0":"38220090","1":""},"MRP/ Marginal":{"0":"849.00/NO","1":""},"Quantity":{"0":"30 NO 30 NO","1":""},"Rate":{"0":"470.00","1":""},"per":{"0":"NO","1":""},"Amount":{"0":"14,100.00","1":"846.00 "}}
I want to convert it into
[{Amount: "14,100.00",Description of Goods: "LTD",HSN/SAC: "38220090",MRP/ Marginal:"849.00/NO",Quantity: "30 NO 30 NO",Rate: "470.00",SI: "1",per: "NO"} ,{Amount: "",Description of Goods: "TET",HSN/SAC: "",MRP/ Marginal:"",Quantity: "",Rate: "",SI: "1",per: "",Amount : "846.00 "}]
Here in object there are 2 rows but It can be more.
Upvotes: 0
Views: 297
Reputation: 24638
You can use for ... of
with Object.entries(obj)
as follows:
let oOld = {"SI":{"0":"1","1":""},"Description of Goods":{"0":"LTD","1":"TET"},"HSN/SAC":{"0":"38220090","1":""},"MRP/ Marginal":{"0":"849.00/NO","1":""},"Quantity":{"0":"30 NO 30 NO","1":""},"Rate":{"0":"470.00","1":""},"per":{"0":"NO","1":""},"Amount":{"0":"14,100.00","1":"846.00 "}};
let oNew = [];
for(let [key,value] of Object.entries(oOld)) {
for(let [k,v] of Object.entries(value)) {
if( !oNew[+k] ) {
oNew.push({});
}
oNew[+k][key] = v;
}
}
console.log( oNew );
Alternatively, you can use the .map()
and .reduce()
methods as follows:
let oOld = {"SI":{"0":"1","1":""},"Description of Goods":{"0":"LTD","1":"TET"},"HSN/SAC":{"0":"38220090","1":""},"MRP/ Marginal":{"0":"849.00/NO","1":""},"Quantity":{"0":"30 NO 30 NO","1":""},"Rate":{"0":"470.00","1":""},"per":{"0":"NO","1":""},"Amount":{"0":"14,100.00","1":"846.00 "}};
let oNew = Object.entries(oOld).map(([key,value]) => ([key,Object.entries(value)])).map(([key,value]) => value.map(val => ({[key]:val[1]}))).reduce((acc,val) => val.map((v,i) => (acc[i] || acc.push([])) && acc[i].concat(v)), []).map(a => a.reduce((acc,val) => Object.assign(acc,val),{}));
console.log( oNew );
Upvotes: 1