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

问题描述

  

  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只返回匹配的子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 05:33