从Node.js中Object的键值中提取值

时间:2015-12-07 20:09:03

标签: javascript node.js

我试图从JSON消息的键值对中提取所有值,然后连接。我在同一个论坛上引用了一些其他问题后尝试使用下面的代码片段。它正在工作,第一个键是打印,但是为了价值,它给了[对象对象],即,它无法解析"员工"键。

如何在Node JS中的单个字符串中提取所有值并进行连接。就业名字String = John Doe | Anna Smith | PeterJones。

评论代码是第二种方式,我试图提取值,但它也不起作用。

感谢。

var text = '{ "employees" : [' +
  '{ "firstName":"John" , "lastName":"Doe" },' +
  '{ "firstName":"Anna" , "lastName":"Smith" },' +
  '{ "firstName":"Peter" , "lastName":"Jones" } ]}';

var obj = JSON.parse(text);
console.log(typeof obj);

for (var key in obj) {
  console.log(' name=' + key + ' value=' + obj[key]);
}

/*
for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    var obj1 = obj[key];
    console.log(obj[key]);

    for (var prop in obj1) {
      if(obj1.hasOwnProperty(prop))
      {
        console.log(obj[prop]);
      }
    }
  }
}
*/

2 个答案:

答案 0 :(得分:5)

var obj = {
  employees: [
    { firstName: "John",
      lastName: "Doe"
    },
    { firstName: "Anna",
      lastName: "Smith"
    },
    { firstName: "Peter",
      lastName: "Jones"
    }
  ]
}

var names = obj.employees.map(function (employee) {
  return employee.firstName + ' ' + employee.lastName;
});

console.log(names);
// => [ "John Doe", "Anna Smith", "Peter Jones" ]

如果真的只想连接所有值而不考虑订单,可以这样做:

var concatenatedValues = obj.employees.map(function (employee) {
  return Object.keys(employee).map(function(key) {
    return employee[key];
  }).join(' ');
});

...但请注意,您最终可能会使用"Doe John"等。

答案 1 :(得分:1)

var text = '{ "employees" : [' +
  '{ "firstName":"John" , "lastName":"Doe" },' +
  '{ "firstName":"Anna" , "lastName":"Smith" },' +
  '{ "firstName":"Peter" , "lastName":"Jones" } ]}';

var obj = JSON.parse(text);
console.log(typeof obj);

for (var key in obj.employees) {
  console.log(' name=' + obj.employees[key].firstName + ' value=' + obj.employees[key].lastName);
};