推荐关注
› Meteor
› JSLint - a JavaScript code quality tool
› jsFiddle
› D3.js
› WebStorm
推荐书目
› JavaScript 权威指南第 5 版
› Closure: The Definitive Guide
yangwenqian

求助,如何在 json 中检索数据?

  •  
  •   yangwenqian · Feb 27, 2017 · 5032 views
    This topic created in 3542 days ago, the information mentioned may be changed or developed.
    var data = [{
     id: 1,
     value: 2532,
     son: [{
      id: 5,
      value: 543,
      son: [{
       id: 46,
       value: 999879,
       son: [{
        id: 12,
        value: 903,
        son: []
       }]
      }]
     }]
    }, {
     id: 3,
     value: 4684,
     son: [{
      id: 11,
      value: 65,
      son: []
     }, {
      id: 45,
      value: 523423,
      son: []
     }]
    }]

    一个无穷节点的 json,深度有几十级,超大,我要查询 id 为 46 的 value 是多少,求一个 js 函数,谢谢。
    8 replies  •  2017-03-03 18:15:06 +08:00
    Cbdy
    Cbdy
    Feb 28, 2017 via Android
    1
    做成一个 b 树?
    czheo
    czheo
    Feb 28, 2017
    2
    function search(id, data) {
    data.forEach( d => {
    if (d.id == id) {
    console.log(d.value)
    }
    search(id, d.son)
    })
    }

    search(46, data)
    vcfvct
    vcfvct
    Feb 28, 2017 via Android
    3
    放到 NoSQL 里面,随便 query 。 MongoDB , elastic search 什么什么的,都可以
    XiaoFaye
    XiaoFaye
    Feb 28, 2017❤️1
    4
    整个 JSON 就是一个字符串,你直接 indexOf 不行吗?别把简单问题复杂化呀。
    zael
    zael
    Feb 28, 2017 via Android
    5
    lodash?
    spark
    spark
    Feb 28, 2017
    6
    递归
    lhstock
    lhstock
    Feb 28, 2017
    7
    function a(data, id) {
    var value;

    function forEachs(arr) {

    arr.forEach(function(d) {
    find(d, id);
    d.son != 0 && forEachs(d.son) // : find(d.sum);

    })

    }

    function find(d, id) {
    if(d.id == id) {
    value = d.value
    }
    }

    forEachs(data);
    return value
    }

    console.log(a(data, 46));
    genesischou
    genesischou
    Mar 3, 2017
    8
    function search(array, id, temp) {
    let data = array.concat(),
    result = temp || {};
    data.forEach(item => {
    if (item.id === id) {
    result = item;
    return;
    } else if (Object.prototype.toString.call(item.son) === '[object Array]' &&
    item.son.length) {
    result=search(item.son, id, result);
    }
    })
    return result;
    }
    search(data, 46);//{ id: 46, value: 999879,son: [ { id: 12, value: 903, son: [] } ] }
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1857 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 15:46 · PVG 23:46 · LAX 07:46 · JFK 10:46
    ♥ Do have faith in what you're doing.