gpt4 book ai didi

javascript - 递归过滤/减少嵌套对象

转载 作者:行者123 更新时间:2023-11-30 11:05:23 25 4
gpt4 key购买 nike

我有一个深层嵌套的对象,我需要搜索它以删除某些键。要删除的键存储在 removeKeys 数组中指示的数组中。目前,该函数仅过滤顶级对象,但对其余对象进行精细缩放,只是不过滤子对象。如何正确减少整个对象以获得所需的输出?

初始未过滤的对象:

let item = {
"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 filterObject = filterNestObject(item);

function filterNestObject(item) {
return Object.keys(item)
.filter(key => {
if (typeof item[key] === 'object') filterNestObject(item[key]);

if (!removeKeys.includes(key)) return true;

return false
})
.reduce((object, key) => {
return {
...object,
[key]: item[key]
};
}, {});

}

预期结果是:

{
"id": "test",
"styles": {
"styles": {
"test": {
"test": "test",
"test1": {
"image": {
"value": "test",
"id": ""
}
}
}
}
},
"test": {
"test": []
}
}

最佳答案

代码中的错误是您在 filter 回调中进行了递归调用。但是你会丢失从递归调用返回的对象。而是将其放在 reduce 回调中。

一个小修正:要测试一个值是否是一个对象,仅仅执行 typeof item[key] === "object" 是不够的,因为 null 也会通过那个测试。这是改编后的代码:

function filterNestObject(item) {
return Object.keys(item)
.filter(key => !removeKeys.includes(key))
.reduce((acc, key) => {
return Object.assign(acc, {
[key]: Object(item[key]) === item[key] ? filterNestObject(item[key]) : item[key]
});
}, Array.isArray(item) ? [] : {});
}

const item = {"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 filterObject = filterNestObject(item);
console.log(filterObject);

关于javascript - 递归过滤/减少嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55857148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com