1
我是全新的,以ES6的數組,我有,看起來像對象的數組:嘗試使用ES6過濾和扁平化嵌套對象
locations: [
{
"is_moving": true,
"uuid": "82fa9dda-e57b-4b3f-99a0-a1db98ae4a19",
"timestamp": "2017-08-05T04:48:25.526Z",
"odometer": 0,
"sample": true,
"coords": {
"latitude": 32.7323862,
"longitude": -117.1939315,
"accuracy": 1000,
"speed": -1,
"heading": -1,
"altitude": -1
},
"activity": {
"type": "in_vehicle",
"confidence": 54
},
"battery": {
"is_charging": false,
"level": 0.5
},
"extras": {}
},
{
"event": "motionchange",
"is_moving": true,
"uuid": "57a0146a-28b9-4baf-86de-e037843c2d32",
"timestamp": "2017-08-05T04:48:25.526Z",
"odometer": 0,
"coords": {
"latitude": 32.7323862,
"longitude": -117.1939315,
"accuracy": 1000,
"speed": -1,
"heading": -1,
"altitude": -1
},
"activity": {
"type": "in_vehicle",
"confidence": 54
},
"battery": {
"is_charging": false,
"level": 0.5
},
"extras": {}
}
]
我想結束了是:
locations: [
{
"timestamp": "2017-08-05T04:48:25.526Z",
"odometer": 0,
"latitude": 32.7323862,
"longitude": -117.1939315,
"accuracy": 1000,
"speed": -1,
"heading": -1,
"altitude": -1
},
{
"timestamp": "2017-08-05T04:48:25.526Z",
"odometer": 0,
"latitude": 32.7323862,
"longitude": -117.1939315,
"accuracy": 1000,
"speed": -1,
"heading": -1,
"altitude": -1
}
]
所以我知道我可以做(感謝https://stackoverflow.com/a/39333664/994275)過濾掉,我不想鍵/值對:
locations.map(({ timestamp, odometer, coords }) => ({ timestamp, odometer, coords }))
,我知道我可以做(感謝https://stackoverflow.com/a/33037683/994275)扁平化的對象:
Object.assign(
{},
...function _flatten(location) {
return [].concat(...Object.keys(location)
.map(k =>
typeof location[k] === 'object' ?
_flatten(location[k]) :
({[k]: location[k]})
)
);
}(location)
)
但我試圖將兩者結合起來,並慘遭失敗。我在地圖中添加了平鋪,但這只是返回一個未定義的數組。
我確定有一個簡單的解決方法,但它在這一點上無法解決。任何幫助將不勝感激!
這裏是工作(感謝誰似乎已經消除了他們的意見的用戶):
let newLocations = locations.map(({ is_moving, uuid, timestamp, odometer, coords }) => ({ is_moving, uuid, timestamp, odometer, coords }));
let test = newLocations.map((location) => {
return Object.assign(
{},
...function _flatten(location) {
return [].concat(...Object.keys(location)
.map(k =>
typeof location[k] === 'object' ?
_flatten(location[k]) :
({[k]: location[k]})
)
);
}(location)
)
});
有沒有辦法凝聚過濾和扁平化?
謝謝!不僅僅是爲了答案,而是爲了向ES6 noob解釋它! – JulieMarie