如何通过 Javascript 中的键名和值获取 json 的 children 部分?

how can i get a children part of a json by keyname and value in Javascript?

我有一个 json 喜欢:

var jsonData = {
    "id": 0,
    "content": "abc",
    "children" : [{
        "id": 1,
        "content": "efg",
        "children" : []
        }
        {
        "id": 2,
        "content": "hij",
        "children" : []
        }
    ]}

我只想通过搜索正确的键和值来获得 json 的 children 部分。 喜欢

 if(id == 2)

然后我可以得到jsonData.children[1],然后我可以在这个object上做其他事情我得到了。 这就像一种更有效的方式,例如 indexOf()

这让我想起了在 Java 和 C# 中使用 Hashtable。好吧 javascript 似乎没有哈希表。

那么,有什么办法可以解决这个问题吗?

您可以使用 filter:

var idToMatch = 2;
var matches = jsonData.children.filter(function (el) {
    return el.id === idToMatch;
});

更新:添加递归案例

将其扩展到递归情况,以至少提供一种替代方法,以从上面@elclanrs 的答案(这是这里的最佳答案)中获得更优雅的方法,但添加以下内容只是为了完整性。

var matches = [];
function findMatches(children, idToMatch) {
    if (children && Array.isArray(children)) {
        var newMatches = children.filter(function (el) {
            return (el.id === idToMatch);
        });
        Array.prototype.push.apply(matches, newMatches);
        for (var i = 0; i < children.length; i++)
            findMatches(children[i].children, idToMatch);
    }
}
findMatches(jsonData.children, 3);
console.log(matches);

JS Fiddle: http://jsfiddle.net/vafwg3kf/

您可以使用递归和减速器:

function find(pred, coll) {
  return coll.reduce(function(acc, obj) {
    if (pred(obj)) {
      return obj
    } else if (obj.children.length) {
      return find(pred, obj.children)
    } else {
      return acc
    }
  },null)
}

find(function(o){return o.id===2}, [jsonData])
//^ {id: 2, content: 'hij', children: []}

如果没有找到具有该 ID 的对象,那么它将 return null

Javascript 对象默认为地图。例如,

var child = {}
child[1] = {"id": 1, "content": "efg"}
child[2] = { "id": 2,"content": "hij"}

您可以像这样检索值

var value = child[1].content;

希望对您有所帮助!

这或许是一种方式。 它的灵感来自@Jason W 、@Mr.Green 和@elclanrs .

我试过了,确实有效。

然而,对于为什么它可以这样工作,仍然有一些问题让我感到困惑,我稍后会 post 我的问题。如果你能帮到我,请检查一下。

var dataMap = {};

function matchData (jsonObj) {
  dataMap[jsonObj.id] = jsonObj;

  if (jsonObj.children.length > 0) {
    for (var i = 0; i < jsonObj.children.length; i++) {
      dataMap[jsonObj.children[i].id] = jsonObj.children[i];

      if (jsonObj.children[i].children > 0) {
        matchData(jsonObj.children[i]);
      }
    }
  }
}

matchData(jsonData);
console.log(dataMap[2]); 
//you will get "{"id": 2,"content": "hij","children" :[]}