如何在JavaScript中以数组形式返回对象的特定属性

时间:2019-06-01 13:23:13

标签: javascript

我有一个函数,它接收一个狗对象数组,并返回一个狗品种为GermanShepherd的所有所有者的名字数组

 E.g. [
      {name: 'Beatrice', breed: 'Lurcher', owner: 'Tom'},
      {name: 'Max', breed: 'GermanShepherd', owner: 'Malcolm'},
      {name: 'Poppy', breed: 'GermanShepherd', owner: 'Vikram'}
    ]
 will return the result in the form of following array 
['Malcolm', 'Vikram']

The code that I have tried
function Owner(dogs) {
     dogs.map(value => {
     if (value.breed === 'GermanShepherd') {
         return value.owner;    
 }
}

1 个答案:

答案 0 :(得分:3)

一种选择是使用reduce(),并检查品种是否与search变量相同(如果相同),请使用concat()添加到累加器中。

let arr = [{"name":"Beatrice","breed":"Lurcher","owner":"Tom"},{"name":"Max","breed":"GermanShepherd","owner":"Malcolm"},{"name":"Poppy","breed":"GermanShepherd","owner":"Vikram"}];
let search = 'GermanShepherd';

let result = arr.reduce((c, v) => v.breed === search ? c.concat(v.owner) : c, []);

console.log(result);


您还可以使用filtermap组合。

let arr = [{"name":"Beatrice","breed":"Lurcher","owner":"Tom"},{"name":"Max","breed":"GermanShepherd","owner":"Malcolm"},{"name":"Poppy","breed":"GermanShepherd","owner":"Vikram"}]
let search = 'GermanShepherd';

let result = arr.filter(o => o.breed === search).map(o => o.owner);

console.log(result);