[英]Get the location of an object in an array with JS/jQuery
假设我有一个如下数组:
[
{
"name": "list",
"text": "SomeText1"
},
{
"name": "complex",
"text": "SomeText2",
"config": {
"name": "configItem",
"text": "SomeText3",
"anotherObject": {
"name": "anotherObject1",
"text": "SomeText4"
}
}
}
]
我正在使用这个很棒的代码来获取具有特定键的所有对象( http://techslides.com/how-to-parse-and-search-json-in-javascript )。 在我的示例中,是getObjects(data,'text','')
,由于文本作为键的出现,它将返回所有节点作为Object。
我唯一的问题是,我需要知道整个数组中返回对象的位置。
有什么办法吗? 还是至少对象的深度与数组有关?
getObjects(r,'text','')[0]
(名称=列表)->深度1
getObjects(r,'text','')[1]
(名称=复杂)->深度1
getObjects(r,'text','')[2]
(name = configItem)->深度2
您将需要遵循以下原则:
function getObjectsDepth(obj, key, val, depth) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjectsDepth(obj[i], key, val,++depth));
} else
//if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
if (i == key && obj[i] == val || i == key && val == '') { //
objects.push(depth);
} else if (obj[i] == val && key == ''){
//only add if the object is not already in the array
if (objects.lastIndexOf(obj) == -1){
objects.push(depth);
}
}
}
return objects;
}
这将返回对象的深度,但不会返回对象本身,仅根据您希望的计数方式传递0或1作为最后一个参数。 如果同时需要对象和深度,则需要obj.push({'obj':obj,'depth':depth})
。
通过此命令更改getObjects函数:
function getObjects(obj, key, val, depth) {
var objects = [];
depth = typeof depth !== 'undefined' ? depth : 0;
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
depth ++;
objects = objects.concat(getObjects(obj[i], key, val, depth));
} else
//if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
if (i == key && obj[i] == val || i == key && val == '') { //
objects.push({"obj":obj,"depth": depth});
} else if (obj[i] == val && key == ''){
//only add if the object is not already in the array
if (objects.lastIndexOf(obj) == -1){
objects.push({"obj":obj,"depth": depth});
}
}
}
return objects;
}
现在您获得了深度和物体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.