gpt4 book ai didi

javascript根据键值过滤嵌套对象

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

我希望通过“step”键的值来过滤嵌套的 javascript 对象:

var data = {
"name": "Root",
"step": 1,
"id": "0.0",
"children": [
{
"name": "first level child 1",
"id": "0.1",
"step":2,
"children": [
{
"name": "second level child 1",
"id": "0.1.1",
"step": 3,
"children": [
{
"name": "third level child 1",
"id": "0.1.1.1",
"step": 4,
"children": []},
{
"name": "third level child 2",
"id": "0.1.1.2",
"step": 5,
"children": []}

]},
]}
]

};

var subdata = data.children.filter(function (d) {
return (d.step <= 2)});

这只会返回未修改的嵌套对象,即使我将过滤器的值设置为 1。.filter 在嵌套对象上工作还是我需要在这里滚动我自己的函数,建议和正确的代码表示赞赏。

最佳答案

递归过滤器函数很容易创建。这是一个示例,它去除了定义的所有项目的 JS 对象 ["depth","x","x0","y","y0","parent","size"] :

function filter(data) {
for(var i in data){
if(["depth","x","x0","y","y0","parent","size"].indexOf(i) != -1){
delete data[i];
} else if (i === "children") {
for (var j in data.children) {
data.children[j] = filter(data.children[j])
}
}
}
return data;
}

如果您想按其他内容进行过滤,只需使用您选择的过滤函数更新第二行。

关于javascript根据键值过滤嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13407728/

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