user11580667
user11580667

Reputation:

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

Upvotes: 0

Views: 115

Answers (1)

Eddie
Eddie

Reputation: 26844

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

Upvotes: 2

Related Questions