Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert row to column Json object

i have bellow json format

const datalist = [{"Week":"01","Apple":8,"Orange":1},
                  {"Week":"02","Orange":9,"Apple":1},
                  {"Week":"03","Apple":10,"Orange":0}];

i want to convert into bellow format

const datalist = [{"Food":"Apple","Week 1":8,"Week 2":1, "Week 3": 10, "Total" : 19},
                  {"Food":"Orange","Week 1":0,"Week 2":9, "Week 3": 0, "Total" :10 }];

i used bellow logic but im not able to get the correct result also the total

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 const convert = toConvert => {
                const map = toConvert.reduce((r, {Week, Apple, Orange}) => {
                  if (r.has(Week))
                    r.set(Week, {...r.get(Week), [Apple]: Orange});
                 else
                     r.set(Week, {Week, [Apple]: Orange});
                  return r;
              }, new Map());
              return [...map.values()];
            };
            
            console.log(convert(datalist));

>Solution :

Just iterate through array of fruits like this:

const datalist = [{"Week":"01","Apple":8,"Orange":1},
                  {"Week":"02","Orange":9,"Apple":1},
                  {"Week":"03","Apple":10,"Orange":0}];

const fruits = datalist.map(f => Object.keys(f).filter(k => k !== "Week"))[0];
let newData = fruits.map((f) => {
  let data = {};
  let total = 0;
  data['Food'] = f;
  datalist.forEach((d)=>{
    data[`Week ${parseInt(d['Week'])}`] = d[f];
    total += d[f];
  });
  data['Total'] = total;
  return data;
});
console.log(newData);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading