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.
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; }
let result = raw.map((obj, i) => {
let newObj = {};
obj.devices.forEach(obj => {
newObj[obj.name] = obj.device_age
});
return {
date: obj.date,
...newObj
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.