使用Node.js解析数组中的对象

时间:2017-01-31 07:45:17

标签: arrays json node.js parsing object

我从数据库接收一个json代码,并将一个对象放入一个数组中。 我找不到如何解析这段代码。 这是json代码:

[ { name: 'John1', surname: 'Doe1' },
  { name: 'John2', surname: 'Doe2' },
  { name: 'John3', surname: 'Doe3' },
  { name: 'John4', surname: 'Doe4' } ]

我想得到姓名和姓氏。

3 个答案:

答案 0 :(得分:1)

因此,您需要为此使用for循环,并且必须遍历每个元素。

以下是如何执行此操作的方法: 首先将数组分配给名为userData的变量。

var userData = [ { name: 'John1', surname: 'Doe1' },
  { name: 'John2', surname: 'Doe2' },
  { name: 'John3', surname: 'Doe3' },
  { name: 'John4', surname: 'Doe4' }]

现在循环遍历数组userData:

for(i=0; i < userData.length; i++) {
    console.log(userData[i].name + ' ' + userData[i].surname);
}

输出将如下:

John1 Doe1
John2 Doe2
John3 Doe3
John4 Doe4

答案 1 :(得分:0)

var arr = [ { name: 'John1', surname: 'Doe1' },
  { name: 'John2', surname: 'Doe2' },
  { name: 'John3', surname: 'Doe3' },
  { name: 'John4', surname: 'Doe4' } ]

for(i=0; i<arr.length; i++) {
    console.log(arr[i].name);
    console.log(arr[i].surname);
}

答案 2 :(得分:0)

将其存储在变量中。这是一个JSON的数组。

var foo = [ { name: 'John1', surname: 'Doe1' },
            { name: 'John2', surname: 'Doe2' },
            { name: 'John3', surname: 'Doe3' },
            { name: 'John4', surname: 'Doe4' } ]

foo[0]{ name: 'John1', surname: 'Doe1' }

现在,foo[0].namefoo[0].surname可用于访问值对。

要以更好的方式执行此操作,请使用loops

希望这有帮助。