如何比较两个具有共同属性的不同数组

How to compare two different arrays with common properties

我有两个数组,一个是不同动物的数组,另一个是动物名称的数组。我想制作动物按钮,每个动物按钮都有自己的颜色,具体取决于它们是什么动物。

我正在使用地图函数,但它并没有真正起作用。

export const animalColors = [
  {
    color: '#FF6800',
    name: 'lion',
  },
  {
    color: '#D80C18',
    name: 'panda',
  },
  {
    color: '#FF8A3D',
    name: 'tiger',
  },
  {
    color: '#02C75A',
    name: 'rabbit',
  },
  {
    color: '#608DF9',
    name: 'bear',
  },
  {
    color: '#0584F6',
    name: 'elephant',
  },
  {
    color: '#222F3E',
    name: 'deer',
  },
  {
    color: '#727272',
    name: 'bird',
  },
  {
    color: '#656598',
    name: 'turtle',
  },
];
const zoo = [
    { id: '1', name: 'lion' },
    { id: '2', name: 'panda' },
    { id: '3', name: 'tiger' },
    { id: '4', name: 'rabbit' },
    { id: '5', name: 'bear' },
    { id: '6', name: 'elephant' },
    { id: '7', name: 'deer' },
    { id: '8', name: 'bird' },
    { id: '9', name: 'turtle' },
]

下面是打字稿的代码。

data.docs 是名为 zoo 的数组。

const BoardItemCard = ({ data }: BoardItemCardProps) => {

  return (
    <div className="BoardItemCard">
      {data &&
        data.docs.map((item: Item, i: number) => {

          return (
            <button style={{backgroundColor: ????}}>
             {item.name}
            </button>
           )

您可以使用array.find()得到对应的颜色:

<button style={{backgroundColor: animalColors.find(x => x.name === item.name)?.color || 'defaultColor'}}>
            {item.name}
</button>

使用JS内置的数组迭代方法就可以了:

var result1 = [
    {id:1, name:'Sandra', type:'user', username:'sandra'},
    {id:2, name:'John', type:'admin', username:'johnny2'},
    {id:3, name:'Peter', type:'user', username:'pete'},
    {id:4, name:'Bobby', type:'user', username:'be_bob'}
];

var result2 = [
    {id:2, name:'John', email:'johnny@example.com'},
    {id:4, name:'Bobby', email:'bobby@example.com'}
];

var props = ['id', 'name'];

var result = result1.filter(function(o1){
    // filter out (!) items in result2
    return !result2.some(function(o2){
        return o1.id === o2.id;          // assumes unique id
    });
}).map(function(o){
    // use reduce to make objects with only the required properties
    // and map to apply this to the filtered array as a whole
    return props.reduce(function(newo, name){
        newo[name] = o[name];
        return newo;
    }, {});
});

document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) +
        '</pre>';