使用array.some只返回匹配的子对象 [英] Use array.some to return only matching sub-objects

查看:82
本文介绍了使用array.some只返回匹配的子对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆