【问题标题】:Nodejs - Correct way to iterate through nested JSON arrayNodejs - 迭代嵌套 JSON 数组的正确方法
【发布时间】:2014-03-28 09:54:46
【问题描述】:

考虑以下示例 JSON 数组:

[{
    info: {
        refOne: 'refOne',
        refTwo: [{
            refOne: 'refOne',
            refTwo: 'refTwo'
        }]
    }
}, {
    info: {
        refOne: 'refOne',
        refTwo: [{
            refOne: 'refOne',
            refTwo: 'refTwo'
        }]
    }
}]

上面的 JSON 是数据库查询响应的简单表示,Nodejs 中循环遍历父信息数组中的每个 'refTwo' 数组的正确方法是什么?

sudo 示例: 对于示例 JSON 中的每个项目 对于当前项目中的每个 refTwo 项目 做点什么

我怀疑这里可能需要“异步”库,但非常感谢一些建议。

【问题讨论】:

    标签: javascript json node.js


    【解决方案1】:

    这是一个简单的 javascript 问题:

    var o = [...];
    
    var fn = function (e){
        e.refOne...
        e.refTwo...
    };
    
    o.forEach (function (e){
        e.info.refTwo.forEach (fn);
    });
    

    【讨论】:

    • 感谢您的及时回复。
    【解决方案2】:

    您可以使用underscorelodash 以功能方式执行此操作。

    例如看看Collections.eachCollections.map

    var _ = require('underscore');
    
    var result = // your json blob here
    
    var myRefs = _.map(results, function(value, key) {
      return value.info.refTwo;
    };
    // myRefs contains the two arrays from results[0].info.refTwo from results[1].info.refTwo now
    
    // Or with each:
    _.each(results, function(value, key) {
      console.log(value.info.refTwo);
    }
    
    // Naturally you can nest, too:
    _.each(results, function(value, key) {
      _.each(value.info.refTwo, function(innerValue) { // the key parameter is optional
        console.log(value);
      }
    }
    

    编辑:您当然可以使用 Gabriel Llamas 建议的 forEach 方法,但我还是建议您查看下划线。

    【讨论】:

    • 感谢您提供替代方法。我会跟进并阅读。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2021-07-13
    • 1970-01-01
    相关资源
    最近更新 更多