TransWikia.com

How can we convert an nested object in an array into an array?

Stack Overflow Asked by Raghu on December 9, 2021

I have the object as below:

const givenData = {
        "ProcessA": { "state": "on", "used": "16.41" },
        "ProcessB": { "state": "off", "used": "16.40" },
        "ProcessC": { "state": "off", "used": "16.36" },
        "ProcessD": { "state": "on", "used": "16.45" }
  };

And I want my output as below two different objects:

  let ob1= {
     "ProcessA":"on",
     "ProcessB":"off",
     "ProcessC":"off",
     "ProcessD":"on",
   }

  let obj2={
     "ProcessA":"16.41",
     "ProcessB":"16.40",
     "ProcessC":"16.36",
     "ProcessD":"16.45",
   }

can anyone suggest me if there is any easy solution for this?

3 Answers

You can achieve using reduce and Object.keys:

const givenData = {
    "ProcessA": { "state": "on", "used": "16.41" },
    "ProcessB": { "state": "off", "used": "16.40" },
    "ProcessC": { "state": "off", "used": "16.36" },
    "ProcessD": { "state": "on", "used": "16.45" }
};

const {obj1, obj2} = Object.keys(givenData).reduce((acc, cur) => ({obj1:{...acc.obj1, [cur]: givenData[cur].state}, obj2:{...acc.obj2,[cur]:givenData[cur].used}}), {});

console.log(obj1)
console.log(obj2)

Answered by Ravi Kukreja on December 9, 2021

Here is what you want:

const givenData = {
    "ProcessA": { "state": "on", "used": "16.41" },
    "ProcessB": { "state": "off", "used": "16.40" },
    "ProcessC": { "state": "off", "used": "16.36" },
    "ProcessD": { "state": "on", "used": "16.45" }
};

const a = {};
const b = {};
for (k in givenData) {
    a[k] = givenData[k].state;
    b[k] = givenData[k].used;
}
console.log(a, b)

Answered by 8HoLoN on December 9, 2021

You can create a reusable function to achieve this:

function getObj(obj, givenKey) {
  return Object
           .keys(obj)
           .reduce((final, key) => ({ ...final, [key]: obj[key][givenKey] }), {})
}

const obj1 = getObj(givenData, "state")
const obj2 = getObj(givenData, "used")

Answered by Muhammad Ali on December 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP