[英]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. 一种选择是使用reduce()
并检查品种是否与search
变量相同(如果相同reduce()
,请使用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);
You can also use filter
and map
combo. 您还可以使用filter
和map
组合。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.