Home > database >  Get key and value from Nested Object
Get key and value from Nested Object

Time:10-27

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

But I got wrong format.

CodePudding user response:

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)

CodePudding user response:

You could use Array#reduce for it.

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

const res = Object.entries(obj.data).reduce((acc, [key, obj]) => ({
  ...acc,
  [key]: obj.value,
}), {});

console.log(res);

  • Related