简体   繁体   中英

How can generate an object, catching the user's id and put in my result?

i am building a structure, i am getting the value if exist the key in both objets, 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 = [{id:1,brand: 'RET'},{id:2,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) } } console.log(brands)

but i want this result:

{
  "TYS": {
    "value": 81,
    "exist": false
  },
  "RET": {
    "id":1,
    "value": 62,
    "exist": true
  },
  "CAT": {
    "id":2,
    "value": 90,
    "exist": true
  },
  "NK": {
    "value": 87,
    "exist": false
  }
}

I want to grab the user id and put it in the result object, I don't want to do any more iterations.

Key your array by brand so you construct an object with brand as a key, I think that will help you accesing values quickly and asking rapidly for an id without more iterations, you could try this:

 const users = [{id:1,brand: 'RET'},{id:2,brand: 'CAT'}]; let brands = {TYS: 81,RET: 62,CAT: 90,NK: 87,}; const brandUsers = users.reduce((acc, usr) => ({...acc, [usr.brand]: usr }), {}); console.log(brandUsers); for(const [key, value] of Object.entries(brands)){ const user = brandUsers[key]; const baseValue = { value, exist: ?.user } brands[key] = user?:id. { id, user.id. .:;baseValue }. baseValue; } console.log(brands)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM