如何使用node.js在嵌套的json数组中打印值?

时间:2017-03-28 02:26:06

标签: javascript arrays json node.js

我有这个json数组。

submit

在这里,我试图通过这样做来控制记录每个消息的值。

[ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ]

输出

jsonArray.forEach(function(element) {
    console.log(element);
    console.log(element['0']);
});

问题是,我如何打印msg键的值以及为什么它返回undefined?

4 个答案:

答案 0 :(得分:1)

您可以使用 lodash

var array = [ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ];

_.mapValues(array, function(array2) {
  _.mapValues(array2, function(array3){
    console.log(array3.msg)})
  })

这将返回'msg'键中的值。这是lodash文档。 loadh-map

答案 1 :(得分:0)

显然你没有任何问题。

退房:https://repl.it/Gh3i/0

如果点击“运行”即可

helloworld1
helloworld2

如果使用整数,则同样适用:

var jsonArray = [ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ];
jsonArray.forEach(function(element) {
   console.log(element[0].msg);
});

答案 2 :(得分:0)

请查看下面附带的更新代码



Outside Before Function: 1
Inside Function: 100
Outside After Function: 100




答案 3 :(得分:0)

尝试再次解析数据,如下所示:

var jsonArray = [ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ]
jsonArray = JSON.parse(JSON.stringify(jsonArray));
jsonArray.forEach(function(element) {
  console.log(element['0'].msg);
});

JSON.stringify应将数据转换为字符串,然后JSON.parse将其转换为JS对象。