1

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.

Cecilia Chan
  • 679
  • 2
  • 8
  • 17
  • 1
    Possible duplicate of [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Liam Aug 30 '17 at 10:06
  • `obj.devices.map` returns an array, a computed property name will be coerced into a string or a symbol. – Sebastian Simon Aug 30 '17 at 10:06

2 Answers2

2

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • because `Object.assign` combines objects to a single object. you can get the devices as objects with age and get only one object back. – Nina Scholz Aug 30 '17 at 10:27
0
let result = raw.map((obj, i) => {
    let newObj = {};
    obj.devices.forEach(obj => {
        newObj[obj.name] = obj.device_age

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