How can i match an value of the arrays object with another object?

Viewed 39

i have this arrays about users and i have another object about brands, but i want to match user's brand with brands

let users = [{
  ...data
  brand: 'RET'
},
{
  ...data
  brand: 'CAT'
}
]

this is the brands object

let brands = {
  TYS: 81,
  RET: 62,
  CAT: 90,
  NK:  87,
}

if an user have the brand then i have to mark yes is brands like this

let brands = {
  TYS: {
    value: 81,
    exist: 'No'
  },
  RET: {
    value: 62,
    exist: 'Yes'
  },
  CAT: {
    value: 90,
    exist: 'Yes'
  },
  NK: {
    value: 90,
    exist: 'No'
  }

}
2 Answers

You can loop over the entries of the object and use Array#some to check if each brand exists.

let users = [{brand: 'RET'},{brand: 'CAT'}]
let brands = {TYS: 81,RET: 62,CAT: 90,NK:  87,}
for(const [key, value] of Object.entries(brands)){
    brands[key] = {
        value, exist: users.some(({brand})=>brand===key) ? 'Yes': 'No'
    }
}
console.log(brands)
.as-console-wrapper{max-height:100%!important;top:0}

You can do that like ...

Object.keys(brands).forEach((brand) => {
  brandsData[brand] = {
    value: brands[brand],
    exists: users.find((user) => user.brand == brand) ? "Yes" : "No",
  };
});

let users = [
  {
    brand: "RET",
  },
  {
    brand: "CAT",
  },
];

let brands = {
  TYS: 81,
  RET: 62,
  CAT: 90,
  NK: 87,
};

let brandsData = {};

Object.keys(brands).forEach((brand) => {
  brandsData[brand] = {
    value: brands[brand],
    exists: users.find((user) => user.brand == brand) ? "Yes" : "No",
  };
});

console.log(brandsData);

if you want to change brands object itself, then replace brandsData with brands in the code.

Related