简体   繁体   English

从数组获取对象值-NodeJs

[英]Get object values from array - NodeJs

I have this array of objects 我有这一系列的对象

[ { id: '573267d06b2957ab24c54d59' },
  { id: '573267d06b2957ab24c54d5a' },
  { id: '573267d06b2957ab24c54d5b' },
  { id: '573267d06b2957ab24c54d5c' },
  { id: '573267d06b2957ab24c54d5d' } 
]

I wish to convert it to the following in NodeJs 我希望将其转换为NodeJs中的以下内容

[ '573267d06b2957ab24c54d59',
  '573267d06b2957ab24c54d5a',
  '573267d06b2957ab24c54d5b',
  '573267d06b2957ab24c54d5c',
  '573267d06b2957ab24c54d5d'
]

It seems like it should be easy given the right library/package, but I am struggling to find the right wording to "flatten" the array into the IDs of the contained objects. 给定正确的库/程序包似乎应该很容易,但是我正在努力寻找正确的措辞以将数组“展平”为所包含对象的ID。

Say your array of objects is called arr , just do this: 假设您的对象数组称为arr ,只需执行以下操作:

var arrayOfStrings = arr.map(function(obj) {
    return obj.id;
});

map will iterate over the array and create a new array based on how you define your function. map将遍历数组并根据您定义函数的方式创建一个新数组。 In this case we return the value of the id key in each case to build out the desired array of ids. 在这种情况下,我们分别返回id键的值以构建所需的id数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM