Besart Marku
Besart Marku

Reputation: 543

Transform an object of objects to an array (special example)

I am trying to transform an object of objects into an array of objects. Basically I want to transform this:

    sales_over_time_week: {
          "1": {
            "orders": 96,
            "total": 270240
          },
          "2": {
            "orders": 31,
            "total": 74121
          }
        }

into this:

[
    {name: 1, orders:96, total:270240}, 
    {name:2, orders:31, total: 74121}
]

To just transform it normally I would do this

     var myData = Object.keys(items).map(key => {
        return items[key];
      });

and it would give me

[
    {1: {orders: 31, total: 74121}},
    {2: {orders: 52, total: 180284}}
]

but my example is a bit special

Upvotes: 3

Views: 59

Answers (2)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92367

Try

Object.keys(data).map(k=> ({name:+k, ...data[k]}));

data = {
      "1": {
        "orders": 96,
        "total": 270240
      },
      "2": {
        "orders": 31,
        "total": 74121
      }
    }
    
let r = Object.keys(data).map(k=> ({name:+k, ...data[k]}));

console.log(r);

Upvotes: 2

mickl
mickl

Reputation: 49945

You can use Object.entries with .map()

let data = {
      "1": {
        "orders": 96,
        "total": 270240
      },
      "2": {
        "orders": 31,
        "total": 74121
      }
    };
    
 let result = Object.entries(data).map(([key, value]) => ({name: key, ...value}));
 console.log(result);

Upvotes: 5

Related Questions