【问题标题】:how can i get a children part of a json by keyname and value in Javascript?如何通过 Javascript 中的键名和值获取 json 的子部分?
【发布时间】:2015-09-27 05:06:49
【问题描述】:

我有一个像这样的 json:

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

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

 if(id == 2)

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

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

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

【问题讨论】:

  • 这个问题对我来说不是很清楚。您想按 id 搜索根 json,或按 id 搜索任何内部对象。例如,如果只有最上面的 json,那么如果按 0 搜索,它应该返回整个对象。如果您只想搜索它的孩子,那么搜索应该返回第一个孩子。如果你想搜索所有 id 为 0 的东西,那么它应该同时返回
  • 我只想通过 id 搜索根 json,这是唯一的,这样我就可以将新的 objectA 添加到对象的(其 id 是正确的)孩子

标签: javascript json hashtable


【解决方案1】:

你可以使用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 小提琴:http://jsfiddle.net/vafwg3kf/

【讨论】:

  • 当正确的对象是jsonData.children[i].children[j]...时会起作用吗?
  • 不,这不是递归的,不会得到嵌套子级的子级。我建议 elclanrs 的答案是递归地选择嵌套的孩子。
  • @Pencil_Case - 为了完整起见,我添加了递归案例。我仍然会接受上面 elclanrs 的答案,但继续完成了这个答案,所以至少它是完整的并且可以帮助其他人。
【解决方案2】:

你可以使用递归和reducer:

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 的对象,则它将返回 null

【讨论】:

    【解决方案3】:

    Javascript 对象默认是 Maps。例如,

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

    你可以像这样检索值

    var value = child[1].content;
    

    希望这会有所帮助!

    【讨论】:

      【解决方案4】:

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

      我试过了,确实有效。

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

      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" :[]}
      

      【讨论】:

        猜你喜欢
        • 2018-04-18
        • 2017-04-29
        • 2013-09-25
        • 2012-04-12
        • 2012-07-20
        • 2021-12-25
        • 2018-10-17
        相关资源
        最近更新 更多