-2

I am new in Javascript, I usually need to handle conversion between object and array, but how can I do it more elegant or clean in ES6/7 such as use Spread syntax or lodash..., rather than use for loop iteration.(since I don't like mutable stuff.)

I want to convert the below object:

{
  book: {
    1001: 'a', 
    1002: 'b', 
    1003: 'c'
  },
  game: {
    1001: 'a'
  }
}

to below array of object:

[
  {
    category: 'book',
    item: [
      { id: 1001, name: 'a' },
      { id: 1002, name: 'b' },
      { id: 1003, name: 'c' }
    ]
  }, 
  {
    category: 'game',
    item: [
      { id: 1001, name: 'a' }
    ]
  }
]
wk9876
  • 137
  • 1
  • 6

1 Answers1

2

You could build new objects and map the inner objects as new items.

var data = { book: { 1001: 'a', 1002: 'b', 1003: 'c' }, game: { 1001: 'a' } },
    result = Object
        .entries(data)
        .map(([category, item ]) => 
            ({ category, item: Object.entries(item).map(([id, name]) => ({ id, name })) }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392