简体   繁体   中英

How to return specific properties of objects in form of array in javascript

I have a function that takes an array of dog objects and returns an array of the specific properties

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

One option is using reduce() and check if the breed if same with search variable, if it is, use concat() to add to the accumulator.

 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); 


You can also use filter and map combo.

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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