0

I've got this object:

var obj = {
    family : [{name: 'will', age: 30}, {name: 'husain', age: 12}],
    friends : [{name: 'cody', age: 31}, {name: 'jeff', age: 11}],
    school : [{name: 'daniel', age: 20}, {name: 'carl', age: 15}]
}

convert it into this

var obj = [
    {family : [{name: 'will', age: 30}, {name: 'husain', age: 12}]},
    {friends : [{name: 'cody', age: 31}, {name: 'jeff', age: 11}]},
    {school : [{name: 'daniel', age: 20}, {name: 'carl', age: 15}]}
];

Write now I am using for..in to build a new array and create object with key as key for new object and so on.

I'm doing this right now

var arr = [];

for (let key in obj) {
    arr.push({key: obj[key]})
}
2
  • Without seeing the code you have it's hard to say much. Does your code work? Do you have some performance problems? Commented Jul 2, 2017 at 14:12
  • it works, but it takes a lot of space, and can't help but feel it'd could be simpler Commented Jul 2, 2017 at 14:13

1 Answer 1

4

I think Object.keys is your best option:

var obj = {
    family : [{name: 'will', age: 30}, {name: 'husain', age: 12}],
    friends : [{name: 'cody', age: 31}, {name: 'jeff', age: 11}],
    school : [{name: 'daniel', age: 20}, {name: 'carl', age: 15}]
}
var r = Object.keys(obj).map(x => ({[x]: obj[x]}) )

console.log(r)

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

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.