0

How do you take a data structure like this -

const data = [
  {
    "Country": "Afghanistan",
    "TotalConfirmed": 20917,
    "TotalDeaths": 369,
    "TotalRecovered": 2171,
  },
  {
    "Country": "Albania",
    "TotalConfirmed": 1263,
    "TotalDeaths": 34,
    "TotalRecovered": 945,
  },
  {
    "Country": "Algeria",
    "TotalConfirmed": 10265,
    "TotalDeaths": 715,
    "TotalRecovered": 6799,
  }
];

and refactor it into a label/value but exclude one of the keys.

so if you clicked on data[0]

const piedata =[
        {
            label: 'TotalConfirmed',
            value: 20917,
        },
        {
            label: 'TotalDeaths',
            value: 369,
        },
        {
            label: 'TotalRecovered',
            value: 2171,
        },
    ];

tried this kind of method of mapping the data.

const piedata2 = [];
  (data).map((listValue, i) => {      
    console.log("keyxx", listValue);
    console.log("indexxx", i);

    let obj = {"label": "xxx", "value": "xx"};
    piedata2.push(obj);

  })
console.log("piedata2", piedata2);
9
  • Here you go: jsfiddle.net/khrismuc/buycp9mL Commented Jun 9, 2020 at 20:17
  • that didn't work - jsfiddle.net/kyduco6r -- you would push the data into the function or the index -- I think just the row data should go into the pie -- so like pieData(data[0]) Commented Jun 9, 2020 at 20:21
  • I accidentally didn't save the fiddle in time, but I already fixed it. Check my link again and it will work. Commented Jun 9, 2020 at 20:23
  • function pieData(row) { return Object.entries(row) .filter(([key, value]) => Number.isInteger(value)) .map(([label, value]) => ({ label, value })); } const piedata = pieData(data[0]) Commented Jun 9, 2020 at 20:26
  • jsfiddle.net/kyduco6r/1 -- more like this Commented Jun 9, 2020 at 20:27

2 Answers 2

1

Here is a solution I could think of:

const pieData = (row) => {
    return Object.keys(row)
        .filter(x => x !== 'Country')
        .map(key => ({label: key, value: row[key]}));
}

It is working here: https://jsfiddle.net/paeorbs6/

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

1 Comment

Could you check the jsfiddle. My solution seems to work
0

you can use for-in statement like this :

const piedata2 = [];
for(var i in data[0]) {
   if(i !== "Country") }
      piedata2.push({label : i , value: data[0][i]})
   }
}
console.log("piedata2", piedata2);

2 Comments

jsfiddle.net/kyduco6r -- what about this method - although it didn't seem to work
'i' is not defined no-undef

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.