比如 我有一个
let data=[
{ "id" : "1234",
"key1" : "val1",
"key2" : "val2",
"name" : "someone",
"age" : 39
},
{ "id" : "1234",
"key1" : "val1",
"key2" : "val2",
"name" : "someone",
"age" : 39
}
]
我想过滤掉 key1,key2 得到
[
{ "id" : "1234",
"name" : "someone",
"age" : 39
},
{ "id" : "1234",
"name" : "someone",
"age" : 39
}
]
请问用 js 有什么优雅的处理办法吗?
1
jamesxu 2021-01-14 09:27:27 +08:00 via iPhone
lodash 有个 omit 方法可以参考
|
2
dengshen 2021-01-14 09:30:38 +08:00 via iPhone
map 返回前 delete 不需要的 key 或者只返回需要的 key
|
3
ymmagic1234 OP @dengshen 可以写个例子不?
|
4
xxpandxxp 2021-01-14 09:54:12 +08:00 1
data.map(x=>{delete x['key1'];delete x['key2']})<br>
应该可以 |
5
duowb 2021-01-14 09:54:31 +08:00 1
|
6
dengshen 2021-01-14 09:57:55 +08:00 via iPhone
@ymmagic1234 楼下两个都行
|
7
easonHHH 2021-01-14 09:59:42 +08:00 8
data.map(({ key1, key2, ...other }) => other)
|
8
baxtergu 2021-01-14 10:41:04 +08:00
let data = [
{ "id": "1234", "key1": "val1", "key2": "val2", "name": "someone", "age": 39 }, { "id": "1234", "key1": "val1", "key2": "val2", "name": "someone", "age": 39 } ] let result = data.map(item => { // 过滤出想要保留的 key const fKeys = Object.keys(item).filter(key => !['name', 'age'].includes(key)); // 不改变原有引用对象数据 let newItem = {}; for (let key of fKeys) { newItem[key] = item[key]; } return newItem; }); 指定黑名单就行了,如果是白名单的话用展开操作符可以简化逻辑 |