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

Get key and value from Nested Object

I want to show the key and value from nested object with data :

const obj = {
  "success": true,
  "data": {
    "data1": {
      "label": "label1",
      "value": "value1"
    },
    "data2": {
      "label": "label2",
      "value": "value2"
    }
  }
}

And want to show the data to object like this:

{data1: "value1", data2: "value2"}

I already try this:

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 init = Object.entries(obj.data).map(([key, value]) => {
    const data = `${key}: ${value.value}`;
    return data;
  });

But I got wrong format.

>Solution :

Use the reduce function

const obj = {
  "success": true,
  "data": {
    "data1": {
      "label": "label1",
      "value": "value1"
    },
    "data2": {
      "label": "label2",
      "value": "value2"
    }
  }
}

const list = Object.keys(obj.data).reduce((acc, key) => {
   acc[key] = obj.data[key].value
   return acc
}, {})
console.log( list)
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