Home > Software engineering >  compare array of data and assign a value
compare array of data and assign a value

Time:06-24

Please i want to extract color name from a user id. The user's id have a short string that indicates the color a user will have

These are the possible colors and codes

  • pur => purple
  • ora => orange
  • bla => black
  • pnk => pink

users without color

const users = [
  {
   id: 'u1pur33',
  },
  {
   id: 'u1ora29',
  }
 ]

This is the result i want to achieve

const users = [
  {
   id: 'u1pur33',
   color: 'purple
  },
  {
   id: 'u1ora29',
   color: orange
  }
 ]

This is what i have tried so far. i could only add the color to the object but i can't proceed

// create a new array with color

const newUser = users.map(user => ({...user}), color: '')

// colors
const colors = [
{color: 'purple', colorCode: 'pur'},
{color: 'orange', colorCode: 'ora'},
{color: 'black', colorCode: 'bla'},
{color: 'pink', colorCode: 'pnk'}
]

CodePudding user response:

Open up your map with normal braces like this so you can write some code to determine which color to choose.

const colors = {
    'pur': 'purple'
    ....
};

const newUser = users.map(user => {

    const code = user.id.substring(2, 5);
    return {...user, 'color': colors[code]};
});
  • Related