简体   繁体   English

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

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

I got a json like: 我有一个像这样的json:

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

I just wanna get a children part of a json by searching correct key and value. 我只是想通过搜索正确的键和值来获取json的子元素。 Like 喜欢

 if(id == 2)

then I can get jsonData.children[1] , and then I can do other things on this object I got. 然后我可以获取jsonData.children[1] ,然后可以对获得的该对象执行其他操作。 It's like a more efficient way which like indexOf() 这就像使用indexOf()的更有效的方式

It reminds me of using Hashtable in Java and C#. 它使我想起在Java和C#中使用Hashtable的情况。 Well javascript seems like have no hashtable. 好的javascript似乎没有哈希表。

So, is there any way to solve this problem? 那么,有什么办法可以解决这个问题?

You can use filter : 您可以使用filter

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

UPDATE: Added recursive case 更新:添加了递归的情况

To expand this to the recursive case to at least provide an alternate approach to the much more elegant approach from the answer from @elclanrs above (which is the best answer here), but the below is added just for completeness. 要将其扩展到递归的情况下,至少可以从上面@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/ JS小提琴: http//jsfiddle.net/vafwg3kf/

You can use recursion and a 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: []}

If no object with that id is found then it will return null . 如果未找到具有该ID的对象,则它将返回null

Javascript objects are by default Maps. Javascript对象默认为Maps。 For instance, 例如,

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

you could retrieve the value like 您可以像检索值

var value = child[1].content;

Hope this helps! 希望这可以帮助!

This may be a way. 这可能是一种方法。 It is inspired by @Jason W , @Mr.Green and @elclanrs . 它的灵感来自@Jason W,@ Mr.Green和@elclanrs。

I tried this, and it did work actually. 我试过了,它确实起作用了。

However, there is still some questions confused me about why it could work like this, and i will post my question later. 但是,仍然有一些问题使我感到困惑,为什么它可以这样工作,我将在稍后发布我的问题。 Please check it out if you can help me. 请检查一下是否可以帮助我。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM