I have two arrays which is an array of different animals and an array of name of animals. I want to make animal buttons and each animal buttons have its own color depending on what kind of animal they are.
I was using map functions but it didn't really worked.
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' },
]
These are the codes of typescript right below.
The data.docs is the array called zoo.
const BoardItemCard = ({ data }: BoardItemCardProps) => {
return (
<div className="BoardItemCard">
{data &&
data.docs.map((item: Item, i: number) => {
return (
<button style={{backgroundColor: ????}}>
{item.name}
</button>
)
CodePudding user response:
You can use array.find() to get corresponding color:
<button style={{backgroundColor: animalColors.find(x => x.name === item.name)?.color || 'defaultColor'}}>
{item.name}
</button>
CodePudding user response:
Just using the Array iteration methods built into JS is fine for this:
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:'[email protected]'},
{id:4, name:'Bobby', email:'[email protected]'}
];
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>';