我有这棵树:
{
"id": 0,
"parentId": null,
"name": "Comapny",
"children": [
{
"id": 1235,
"parentId": 0,
"name": "Experiences",
"children": [
{
"id": 3333,
"parentId": 154,
"name": "Lifestyle",
"children": [],
"merchants": [
{
"id": 348,
"name": "Experience Mad"
},
{
"id": 30,
"name": "Virgin Experience Days"
}
]
},
{
"id": 319291392,
"parentId": 318767104,
"name": "Other Experiences",
"children": [],
"merchants": [
{
"id": 353,
"name": "Tasterlab"
},
{
"id": 19,
"name": "Activity Superstore"
}
]
}
],
"merchants": [
{
"id": 35715,
"name": "Red Letter Days"
},
{
"id": 85,
"name": "The Hut"
}
]
}
]
}
我需要通过id找到对象。例如,如果需要找到id为353的对象,我必须得到:
{"id": 353,"name": "Tasterlab"}
如果我需要找到id:1235
的对象,我必须得到:{"id": 1235,"name": "Experiences"}
我尝试了很多次但是考虑到树的复杂性对我来说很难做到我想要的。
答案 0 :(得分:1)
function findId(obj, id) {
if (obj.id == id) {
return obj;
}
if (obj.children) {
for (var i = 0; i < obj.children.length; i++) {
var found = findId(obj.children[i], id);
if (found) {
return found;
}
}
}
if (obj.merchants) {
for (i = 0; i < obj.merchants.length; i++) {
found = findId(obj.merchants[i], id);
if (found) {
return found;
}
}
}
return false;
}
答案 1 :(得分:1)
代码取自:http://techslides.com/how-to-parse-and-search-json-in-javascript/
根据键,值,键和值匹配返回一个对象数组
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 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);
} 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);
}
}
}
return objects;
}
返回与某个键匹配的值数组
function getValues(obj, key) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getValues(obj[i], key));
} else if (i == key) {
objects.push(obj[i]);
}
}
return objects;
}
返回与特定值匹配的键数组
function getKeys(obj, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getKeys(obj[i], val));
} else if (obj[i] == val) {
objects.push(i);
}
}
return objects;
}