0

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.

1
  • This doesn't seem too difficult. What have you tried so far? for ... in would be a start. Commented Sep 9, 2021 at 13:13

1 Answer 1

1

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 );

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.