gpt4 book ai didi

javascript - 嵌套对象中匹配键值对的路径

转载 作者:搜寻专家 更新时间:2023-11-01 04:32:06 25 4
gpt4 key购买 nike

我试图在嵌套对象中实现搜索。

   // Returns an array of matching objects
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (!$.isNumeric(obj[key]) && i == key && obj[key].toLowerCase().match(val)) {
objects.push(obj);
}
}
return objects;
}

该函数根据提供的键值对返回匹配对象。

我想要的是找到键值对的对象的路径。

示例数据

TestObj = {
"Categories": [{
"Product1": [{
"id": "a01",
"name": "Pine",
"description": "Short description of pine."
}, {
"id": "a02",
"name": "Pine",
"description": "Short description of pine."
}, {
"id": "a03",
"name": "Poplar",
"description": "Short description of poplar."
}],
"id": "A",
"title": "Cheap",
"description": "Short description of category A."
}, {
"Product2": [{
"id": "b01",
"name": "Maple",
"description": "Short description of maple."
}, {
"id": "b02",
"name": "Oak",
"description": "Short description of oak."
}, {
"id": "b03",
"name": "Bamboo",
"description": "Short description of bamboo."
}]
}]
};

我正在尝试编写一个函数

function objPath(obj, key, val, path) {
var result = [];
var passName = '';
if (path) {
passName = path;
}
var tempArray = [];
for (var prop in obj) {
var value = obj[prop];
if (typeof value === 'object') {
tempArray = objPath(value, key, val, passName);
$.each(tempArray, function (k, value) {
result.push(value);
});
} else if (prop == key && obj[key].toLowerCase().match(val)) {
result.push(obj[key]);
}
}
return result;
}

如果我将函数调用为

objPath(TestObj, 'id', 'b03');

应该返回 Categories > Product2 > 3rd Row

但我得到的只是 key 。如何修复 objPath 函数以获得所需的结果

最佳答案

我写了一个自定义函数

function objPath(obj, key, val, path) {
var result = [];
var passName = '';
if (path) {
passName = path;
}
var tempArray = [];
for (var prop in obj) {
var value = obj[prop];
if (typeof value === 'object') {
tempArray = objPath(value, key, val, passName);
$.each(tempArray, function (k, value) {
result.push(value);
});
} else if (!$.isNumeric(obj[key]) && prop == key && obj[key].toLowerCase().match(val)) {
result.push(passName + '["' + obj[prop] + '"]');
} else {
if ($.isNumeric(obj[prop])) {
//passName += ' > ' + obj[prop];
} else {
passName += '["' + obj[prop] + '"]';
}
}
}
return result;
}

哪个会返回

["Categories"]["Product2"]["b03"]

关于javascript - 嵌套对象中匹配键值对的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20214798/

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