我正在使用jsTree并且树是一个结构化的JSON对象。
[{
"id": 1,
"text": "TEXT_ONE",
"children": [
{
"id": 2,
"text": "TEXT_TWO",
"children": [
{
"id": 3,
"text": "TEXT_THREE",
"children": [
]
},
{
"id": 4,
"text": "TEXT_FOUR",
"children": [
]
}
]
},
{
"id": 5,
"text": "TEXT_FIVE",
"children": [
]
}
]
},
{
"id": 6,
"text": "TEXT_SIX",
"children": [ ]
}]
我想根据对象的“id”获取对象。
例如,如果我有一个函数getIdFromTree(3),它将返回JSON对象,如下所示:
{
"id": 3,
"text": "TEXT_THREE",
"children": []
},
我是如何在Javascript / JQuery中做到的?
答案 0 :(得分:2)
试试这个
function getObjById (tree, id) {
if(tree.id === id) {
return tree;
}
if(tree.children) {
for(var i = 0, l = tree.children.length; i < l; i++) {
var returned = getObjById(tree.children[i], id);
if(returned) {
// so that the loop doesn't keep running even after you find the obj
return returned;
}
}
}
}
请按以下方式调用
getObjById({children: tree}, 3); // tree is the array object above.
答案 1 :(得分:1)
function findById (tree, id) {
var result, i;
if (tree.id && tree.id === id) {
result = tree;
// Revalidate array list
} else if (tree.length) {
for (i = 0; i < tree.length; i++) {
result = findById(tree[i], id);
if (result) {
break;
}
}
// Check childrens
} else if (tree.children) {
result = findById(tree.children, id);
}
return result;
}
答案 2 :(得分:1)
使用过滤器Methode off Array
data.filter(function(obj){obj.id == 3});
答案 3 :(得分:1)
试试这个.... Es6
function *getObjectById(data, id) {
if (!data) return;
for (let i = 0; i< data.length; i++){
let val = data[i];
if (val.id === id) yield val;
if (val.children) yield *getObjectById(val.children , id);
}
}
现在
getObjectById(arrayOfObjects, id).next().value;
答案 4 :(得分:0)
以最有效和最有效的方式尝试这一点..
function getObjById (tree, id) {
for(var i= 0;i<tree.length;i++)
{
if(tree[i].id===id)
{
return tree[i];
}
if(tree[i].children)
{
var returned = getObjById(tree[i].children,id);
if(returned!= undefined)
return returned;
}
}
};
链接: