如何将数组对象的值与另一个对象匹配?

时间:2021-05-15 04:19:51

标签: javascript

我有这个关于用户的数组,我有另一个关于品牌的对象,但我想将用户的品牌与品牌相匹配

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

这是品牌对象

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

如果用户拥有该品牌,那么我必须标记是这样的品牌

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

}

2 个答案:

答案 0 :(得分:1)

您可以遍历对象的条目并使用 Array#some 检查每个品牌是否存在。

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}

答案 1 :(得分:1)

你可以这样做......

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);

如果您想更改 brands 对象本身,请将代码中的 brandsData 替换为 brands