我试图从JSON消息的键值对中提取所有值,然后连接.我在同一个论坛上引用了一些其他问题后尝试使用下面的代码片段.它正在工作,第一个键是打印,但是对于值,它给出了[object Object],即,它无法解析"Employees"键下的数据.
如何在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]); } } } } */
Jordan Runni.. 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"
等等.
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"
等等.