如何使用 jquery 获取基于键的 JSON 对象

How to get an JSON Object based in key using jquery

我正在使用 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),它将 return 我的 JSON 对象如下:

{        
    "id": 3,
    "text": "TEXT_THREE",
    "children": []
},

我如何在 Javascript/JQuery 中做到这一点?

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;
}

试试这个

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.

尝试以最有效和最高效的方式..

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;
        }
    }
};

link:

https://jsfiddle.net/aa7zyyof/14/

使用数组的过滤方法

data.filter(函数(obj){ obj.id== 3});

试试这个.... 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;