如何使用map方法返回具有特定属性的列表



我有一个如下所示的对象列表,我想使用map返回其中的三个属性。在下面的对象列表中,我想使用map来返回id、名称和estimated_diameter。我该怎么做呢?使用map方法可以实现吗?下面的函数返回一个未定义对象列表。

const listOfObjects.map(o => {
return o.id && o.name && o.estimated_diamer;
});
console.log(listOfObjects); // returns [undefined, undefined, ...]

上面返回[undefined, undefined,…]

对象列表:

[
{
links: {
self: 'http://www.neowsapp.com/rest/v1/neo/3720769?api_key=DEMO_KEY'
},
id: '3720769',
neo_reference_id: '3720769',
name: '(2015 KH157)',
nasa_jpl_url: 'http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=3720769',
absolute_magnitude_h: 19.9,
estimated_diameter: {
kilometers: [Object],
meters: [Object],
miles: [Object],
feet: [Object]
},
is_potentially_hazardous_asteroid: true,
close_approach_data: [ [Object] ],
is_sentry_object: false
},
{
links: {
self: 'http://www.neowsapp.com/rest/v1/neo/2152561?api_key=DEMO_KEY'
},
id: '2152561',
neo_reference_id: '2152561',
name: '152561 (1991 RB)',
nasa_jpl_url: 'http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=2152561',
absolute_magnitude_h: 19,
estimated_diameter: {
kilometers: [Object],
meters: [Object],
miles: [Object],
feet: [Object]
},
is_potentially_hazardous_asteroid: true,
close_approach_data: [ [Object] ],
is_sentry_object: false
},
{
links: {
self: 'http://www.neowsapp.com/rest/v1/neo/3441171?api_key=DEMO_KEY'
},
id: '3441171',
neo_reference_id: '3441171',
name: '(2008 XW2)',
nasa_jpl_url: 'http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=3441171',
absolute_magnitude_h: 20.7,
estimated_diameter: {
kilometers: [Object],
meters: [Object],
miles: [Object],
feet: [Object]
},
is_potentially_hazardous_asteroid: true,
close_approach_data: [ [Object] ],
is_sentry_object: false
},
...
]

只需创建一个新对象,仅包含您正在寻找的值:

const listOfObjects.map(o => {
return { id: o.id, name: o.name, estimated_diamer: o.estimated_diamer };
});

最新更新