-1

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
  • What have you tried so far to solve this on your own? A simple for...in... would be enough (if you know the names of the properties) Commented Jul 23, 2020 at 9:42
  • Read up on Object.entries() and Array.map() Commented Jul 23, 2020 at 9:42
  • I think this your answer. please checked it. stackoverflow.com/questions/44520500/… Commented Jul 23, 2020 at 9:43

3 Answers 3

1

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")
Sign up to request clarification or add additional context in comments.

1 Comment

@Raghu Doing it separately for properties state and used makes the process inefficient. See my answer.
1

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)

1 Comment

Don’t always add “here’s what you want” or nothing to your answers. Instead describe the problem with OPs attempt and the changes you made to fix it.
0

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)

Comments

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.