gpt4 book ai didi

javascript - 使用 javascript 搜索嵌套对象中的特定值并返回仅包含搜索到的项目的更新后的原始对象

转载 作者:行者123 更新时间:2023-12-03 02:27:50 27 4
gpt4 key购买 nike

使用 javascript 搜索嵌套对象中的特定值并返回更新后的原始对象(仅包含搜索到的项目)

 var people= {
"i": [
{
"country": "Australia",
"list": [
{
"name": "ABC ",
"address": "AB street ",
}
]
},
{
"country": "Brazil",
"list": [
{
"name": "XZ ",
"address": "AB street "
},
...
]
}
]
...
};

我想按名称搜索。

最佳答案

使用函数Object.keys()并在key === searchedText时打破最深的循环。

var pages = {  "1": [{    "title": "Australia",    "list": [{        "key": "Base1",        "label": "Base-label",        "description": "description"      },      {        "key": "Base1",        "label": "Base-label",        "description": "description"      }    ]  }],  "2": [{      "title": "Australia",      "list": [{          "key": "Base1",          "label": "Base-label",          "description": "description"        },        {          "key": "Base1",          "label": "Base-label",          "description": "description"        },        {          "key": "Base1",          "label": "Base-label",          "description": "description"        }      ]    },    {      "title": "Netherlands",      "list": [{          "key": "Base1",          "label": "Base-label",          "description": "description"        },        {          "key": "Base2",          "label": "Base-label",          "description": "description"        },        {          "key": "Base1",          "label": "Base-label",          "description": "description"        }      ]    }  ],  "3": [{      "title": "Usa",      "list": [{          "key": "Base2",          "label": "Base-label",          "description": "description"        },        {          "key": "Base1",          "label": "Base-label",          "description": "description"        }      ]    },    {      "title": "Canada",      "list": [{          "key": "Base1",          "label": "Base-label",          "description": "description"        },        {          "key": "Base1",          "label": "Base-label",          "description": "description"        },        {          "key": "Base2",          "label": "Base-label",          "description": "description"        }      ]    }  ]};

var filteredPages = {};
var searchedText = "Base2";
for (var k of Object.keys(pages)) {
for (var o of pages[k]) {
for (var io of o.list) {
if (io.key.toLowerCase().indexOf(searchedText.toLowerCase()) !== -1)  {
filteredPages[k] = filteredPages[k] || [];
filteredPages[k].push({
title: o.title,
list: [io]
});
}
}
}
}

console.log(filteredPages)
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}

关于javascript - 使用 javascript 搜索嵌套对象中的特定值并返回仅包含搜索到的项目的更新后的原始对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48864490/

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