当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《从Node.js中Object的键值中提取值》经验,为你挑选了1个好方法。

我试图从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"等等.



1> Jordan Runni..:
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"等等.

推荐阅读
农大军乐团_697
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有