提问人:RJK 提问时间:11/11/2023 最后编辑:RJK 更新时间:11/11/2023 访问量:34
如果值为 NULL [duplicate],则从对象数组中省略特定键
Omit specific keys from array of objects if the value is NULL [duplicate]
问:
我有这个数组:
[
{
"name": "Homer Simpson",
"age": "43",
"start_time": null,
"end_time": null
},
{
"name": "Bart Simpson",
"age": "14",
"start_time": "2023-11-10T20:08:10Z",
"end_time": "2023-11-10T20:08:10Z"
}
];
如果值为 NULL,如何从每个对象中省略 and?我想以这个数组结束:start_time
end_time
[
{
"name": "Homer Simpson",
"age": "43"
},
{
"name": "Bart Simpson",
"age": "14",
"start_time": "2023-11-10T20:08:10Z",
"end_time": "2023-11-10T20:08:10Z"
}
];
我知道如果时间值为 null,我可以遍历每个对象并使用省略的值推送到一个新数组中,但是有没有更简洁的方法?有没有办法使用 Array.filter?
答:
1赞
Yaroslavm
11/11/2023
#1
执行此操作的简单方法是使用带有函数的映射。lodash
pickBy
它比使用更短、更优雅。reduce
import {map, pickBy} from 'lodash';
const data = [
{
"name": "Homer Simpson",
"age": "43",
"start_time": null,
"end_time": null
},
{
"name": "Bart Simpson",
"age": "14",
"start_time": "2023-11-10T20:08:10Z",
"end_time": "2023-11-10T20:08:10Z"
}
];
const result = map(data, obj => pickBy(obj, (value, key) => value !== null));
评论