使用array.some只返回匹配的子对象 [英] Use array.some to return only matching sub-objects
问题描述
const requestedColours = ['blue', '绿色'];
我将其传递给包含具有各种颜色详细信息的对象的函数:
colorOptions(requestedColours){
const options = {
blue:{
icon:'sea.jpg' ,
标题:'Sea Blue',
},
green:{
图标:'leaf.jpg',
标题:'绿叶',
},
粉色:{
图标:'flower.jpg',
标题:'玫瑰粉',
}
}
return options.some(requestedColours);
}
我知道的以下行不正确:
return options.some(requestedColours);
不过我也试过,例如:
return options.some('blue');
这不会返回 blue的子对象
,如何正确使用 array.some
?
Array#reduce
requestedColours
数组。
注意:一个明智的想法也将是
const requestedColours = ['blue','green']; const options = {blue:{icon:'sea.jpg',title:'Sea Blue',},绿色:{icon:'leaf.jpg',标题:'绿叶',},粉红色:{icon:'flower.jpg',标题:'Rose Pink',}}; const colorOptions =(obj,arr)= > {return requestedColours.reduce((s,a)=> {if(a in options){s [a] = obj [a];} return s;},{});}; console.log(colorOptions选项,requestedColours));
I have a list of requested colours that I am passing to a function:
const requestedColours = ['blue','green'];
I pass this into a function which contains an object with details of various colours:
colorOptions(requestedColours) {
const options = {
blue: {
icon: 'sea.jpg',
title: 'Sea Blue',
},
green: {
icon: 'leaf.jpg',
title: 'Leafy green',
},
pink: {
icon: 'flower.jpg',
title: 'Rose Pink',
}
}
return options.some(requestedColours);
}
The following line I'm aware is incorrect:
return options.some(requestedColours);
However I also tried, for example:
return options.some('blue');
And this does not return the sub-object for blue
, how do I correctly use array.some
?
Array#reduce
over requestedColours
array.
Note: A wise idea would be also moving the options
object outside the function.
const requestedColours = ['blue', 'green'];
const options = {
blue: {
icon: 'sea.jpg',
title: 'Sea Blue',
},
green: {
icon: 'leaf.jpg',
title: 'Leafy green',
},
pink: {
icon: 'flower.jpg',
title: 'Rose Pink',
}
};
const colorOptions = (obj, arr) => {
return requestedColours.reduce((s, a) => {
if (a in options) {
s[a] = obj[a];
}
return s;
}, {});
};
console.log(colorOptions(options, requestedColours));
这篇关于使用array.some只返回匹配的子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!