Cecilia Chan
Cecilia Chan

Reputation: 739

turn array of object into keys failed

I have this structure

  const raw = [{
      date: '2018-8-1',
      devices: [{
        id: 1,
        name: 'iphone',
        device_age: 12
      }, {
        id: 2,
        name: 'samsung',
        device_age: 10
      }]
    }, {
      date: '2018-8-2',
      devices: [{
        id: 1,
        name: 'iphone',
        device_age: 5
      }, {
        id: 2,
        name: 'samsung',
        device_age: 9
      }]
    }]

I want to transform above sturcture into this

[{date: '2018-8-1', iphone: 12, samsung: 10}, {date: '2018-8-2', iphone:5, samsung:9}]

What's wrong with my attempt below?

let result = raw.map((obj, i) => {
   return {
       date: obj.date,
       [obj.devices.map(innerObj => innerObj.name)]: 'test'
   }
})

https://jsfiddle.net/q74x8106/

or I shouldn't use map for inner loop? I'm lost.

Upvotes: 1

Views: 35

Answers (2)

q1246523594
q1246523594

Reputation: 1

let result = raw.map((obj, i) => {
    let newObj = {};
    obj.devices.forEach(obj => {
        newObj[obj.name] = obj.device_age

    });
    return {
        date: obj.date,
        ...newObj
    }
})

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386624

You could map the outer array and build a new object with Object.assign and spread syntax ....

const raw = [{ date: '2018-8-1', devices: [{ id: 1, name: 'iphone', device_age: 12 }, { id: 2, name: 'samsung', device_age: 10 }] }, { date: '2018-8-2', devices: [{ id: 1, name: 'iphone', device_age: 5 }, { id: 2, name: 'samsung', device_age: 9 }] }],
    result = raw.map(({ date, devices }) =>
        Object.assign({ date }, ...devices.map(d => ({ [d.name]: d.device_age }))));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Related Questions