gpt4 book ai didi

javascript - 深入搜索属性值后返回对象

转载 作者:行者123 更新时间:2023-11-30 09:13:47 24 4
gpt4 key购买 nike

我有一个函数可以在嵌套对象中成功搜索属性值中包含的关键字,它返回嵌套对象,但我希望它返回整个对象。

我正在搜索的数组如下所示:

var images = [
{
"node": {
"comments_disabled": false,
"edge_media_to_caption": {
"edges": [
{
"node": {
"text": "this text includes the hashtag #green"
}
}
]
},
"shortcode": "Byqehgyorxq"
}
},
{
"node": {
"comments_disabled": false,
"edge_media_to_caption": {
"edges": [
{
"node": {
"text": "this text includes the hashtag #red"
}
}
]
},
"shortcode": "Byqehgyorxq"
}
}
]

以下代码将返回 { "text": "this text includes the hashtag #red"}

function customFilter(object, result, key, value){
if(object.hasOwnProperty(key) && object[key].includes(value))
result.push(object);

for(var i=0; i<Object.keys(object).length; i++){
if(typeof object[Object.keys(object)[i]] == "object"){
customFilter(object[Object.keys(object)[i]], result, key, value);
}
}
}
var result = []
customFilter(images, result, 'text', 'red');

我希望此函数返回整个节点对象,并具有所需的输出:

"node": { "comments_disabled": false, "edge_media_to_caption": { "edges": [ { "node": { "text": "this text includes the hashtag #red" } } ] }, "shortcode": "Byqehgyorxq"}

更新:修复无效对象

最佳答案

你可以通过查看对象的内部找到该对象。

function filter(array, key, value) {
function find(object) {
if (!object || typeof object !== 'object') return false;
if (key in object && object[key].includes(value)) return true;
return Object.values(object).some(find);
}
return array.find(find);
}

var images = [{ node: { comments_disabled: false, edge_media_to_caption: { edges: [{ node: { text: "this text includes the hashtag #red" } }] }, shortcode: "Byqehgyorxq" } }],
result = filter(images, 'text', 'red');

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

关于javascript - 深入搜索属性值后返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56601103/

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