javascript Nodejs - 迭代嵌套 JSON 数组的正确方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22709354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:37:57  来源:igfitidea点击:

Nodejs - Correct way to iterate through nested JSON array

javascriptjsonnode.js

提问by fearhsonic

Consider the following sample JSON array:

考虑以下示例 JSON 数组:

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

The above JSON is a simple representation of a database query response, What is the correct way within Nodejs to loop through each 'refTwo' array within the parent info array?

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

sudo example: for each item in sample JSON for each refTwo item in current item do something

sudo 示例:对于示例 JSON 中的每个项目,为当前项目中的每个 refTwo 项目做一些事情

I have a suspicion that the 'async' lib may be required here but some advice is much appreciated.

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

回答by Gabriel Llamas

This is a simple javascript question:

这是一个简单的javascript问题:

var o = [...];

var fn = function (e){
    e.refOne...
    e.refTwo...
};

o.forEach (function (e){
    e.info.refTwo.forEach (fn);
});

回答by Otze

You could use underscoreor lodashto do it in a functional way.

您可以使用下划线lodash以功能方式进行操作。

For example have a look at Collections.eachand Collections.map:

例如看看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);
  }
}

Edit: You can of course use the forEach method suggested by Gabriel Llamas, however I'd recommend having a look at underscore nonetheless.

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