3 回答
TA贡献1876条经验 获得超6个赞
这有点hacky,性能也不是很好,所以如果您要处理非常大的对象图,这可能不是一个好的解决方案,但这是在以下方法中使用replacer回调的单线解决方案JSON.stringify:
JSON.parse(JSON.stringify(audience, (k, v) => removeKeys.includes(k) ? undefined : v));
演示:
let audience = {
"label": "test",
"id": "test",
"styles": {
"label": "Styles",
"styles": {
"test": {
"test": "test",
"label": "test",
"test1": {
"label": "test",
"image": {
"label": "test",
"type": "test",
"value": "test",
"autoSelect": "",
"id": ""
}
}
}
}
},
"test": {
"label": "test",
"test": []
}
}
const removeKeys = ["label", "type", "autoSelect"];
let newAudience = JSON.parse(JSON.stringify(audience, (k, v) => removeKeys.includes(k) ? undefined : v));
console.log(newAudience);
同样,如果您要从JSON字符串解析原始对象,则可以使用reviver来自的回调JSON.parse:
let jsonString = `{
"label": "test",
"id": "test",
"styles": {
"label": "Styles",
"styles": {
"test": {
"test": "test",
"label": "test",
"test1": {
"label": "test",
"image": {
"label": "test",
"type": "test",
"value": "test",
"autoSelect": "",
"id": ""
}
}
}
}
},
"test": {
"label": "test",
"test": []
}
}`
const removeKeys = ["label", "type", "autoSelect"];
const audience = JSON.parse(jsonString, (k, v) => removeKeys.includes(k) ? undefined : v);
console.log(audience);
添加回答
举报