user8878908
user8878908

Reputation:

How can I convert this object of objects into an array of objects?

How can I convert this object:

var json = {
    "user3" : {
        "id" : 1
    },
    "user1" : {
        "id" : 3
    },
    "user2" : {
        "id" : 6
    }
}

to this array:

var json = [{
        "name": "user1",
        "id": 3
    }, {
        "name": "user2",
        "id": 6
    }, {
        "name": "user3",
        "id": 1
    }];

Can someone tell me? Or how can I sort an object like the first example?

Upvotes: 0

Views: 119

Answers (4)

AIOT MAKER
AIOT MAKER

Reputation: 584

An alternative approach, using a for-in loop:

const json = {
    "user3": {
        "id": 1
    },
    "user1": {
        "id": 3
    },
    "user2": {
        "id": 6
    }
}

const result = [];

for (const prop in json) {
    result.push({ "name": prop, "id": json[prop].id });
}

console.log(result);

Will provide:

[ { name: 'user3', id: 1 },
  { name: 'user1', id: 3 },
  { name: 'user2', id: 6 } ]

Upvotes: 0

Eddie
Eddie

Reputation: 26844

You can use Object.entries to convert the object into an array. Use map to loop thru the array and use Object.assign to construct the new object.

var json = {
  "user3": {
    "id": 1
  },
  "user1": {
    "id": 3
  },
  "user2": {
    "id": 6
  }
}

var result = Object.entries(json).map(([k, o]) =>Object.assign(o, {name: k}));

console.log(result);

Upvotes: 0

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21851

Try

const src = {
    "user3" : {
        "id" : 1
    },
    "user1" : {
        "id" : 3
    },
    "user2" : {
        "id" : 6
    }
}

const out = Object.keys(src).map((key) => ({name: key, id: src[key].id}))

Upvotes: 2

mightyplow
mightyplow

Reputation: 519

You can use Object.keys() and Array.prototype.reduce() to iterate over the object items and create an array out of the single items.

Object.keys(json).reduce((items, username) => {
const user = json[username];
   return items.concat({
      name: username,
      id: user.id
   });
}, []);

Upvotes: 0

Related Questions