我是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)
)
但是我试图将两者结合起来并且悲惨地失败。我在地图中添加了flatten,但这只是返回一个undefined数组。
我确定这是一个简单的解决方法,但此时它已经躲过了我。任何帮助将不胜感激!
这里有效(感谢似乎已删除评论的用户):
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)
)
});
有没有办法压缩过滤和展平?
答案 0 :(得分:0)
function body of an arrow function有两种语法:一种带有“块体”,另一种带有“简洁体”。当您使用“块体”时,您必须使用花括号{ }
将所包含的语句包围在块中,如果不使用,则需要显式的return
语句想要返回undefined
。
您可以将两个操作合并为一个map
并使用“简洁的正文”语法:
let newLocations = locations.map(({ is_moving, uuid, timestamp, odometer, coords }) =>
Object.assign(
{},
...function _flatten(location) {
return [].concat(...Object.keys(location)
.map(k =>
typeof location[k] === 'object' ?
_flatten(location[k]) :
({[k]: location[k]})
)
);
}({ is_moving, uuid, timestamp, odometer, coords })
)
);