首页 > 解决方案 > 根据特定值识别数组中的唯一对象

问题描述

我有以下对象数组,我需要根据 key 从这个数组中识别唯一对象img1。我能够识别与 key 关联的唯一值,img1但不能识别 key 的关联值img2

我目前拥有的代码,

const imgs_arr = [
    ...new Set(
      input_arr.map(item => {img_1: item.img1[0]})
    )
  ];
  return imgs_arr;

输入数组:

[{img1: ['/path/to/img1'], img2: ['/path/to/img2']},
{img1: ['/path/to/img1'], img2: ['/path/to/img3']},
{img1: ['/path/to/img1'], img2: ['/path/to/img4']},
{img1: ['/path/to/img12'], img2: ['/path/to/img5']},
{img1: ['/path/to/img12'], img2: ['/path/to/img46']},
{img1: ['/path/to/img12'], img2: ['/path/to/img45']},
{img1: ['/path/to/img12'], img2: ['/path/to/img478']}]

预期输出数组:

[{img1: '/path/to/img1', img2: '/path/to/img2'},
{img1: '/path/to/img12', img2: '/path/to/img5'}]

根据评论中的问题为问题添加更多颜色。 img1key 具有我需要从中找到唯一值的值,然后img2从第一个匹配项中找到 key 的相应值。

非常感谢您的帮助!

标签: javascriptarraysvue.jsecmascript-6vuejs2

解决方案


使用forEach循环并使用 unqiue 键构建任何对象。Object.values从构建的对象中获取。

const data = [
  { img1: ["/path/to/img1"], img2: ["/path/to/img2"] },
  { img1: ["/path/to/img1"], img2: ["/path/to/img3"] },
  { img1: ["/path/to/img1"], img2: ["/path/to/img4"] },
  { img1: ["/path/to/img12"], img2: ["/path/to/img5"] },
  { img1: ["/path/to/img12"], img2: ["/path/to/img46"] },
  { img1: ["/path/to/img12"], img2: ["/path/to/img45"] },
  { img1: ["/path/to/img12"], img2: ["/path/to/img478"] }
];

const update = data => {
  const res = {};

  data.forEach(item => {
    const u_key = item.img1[0];
    if (!(u_key in res)) {
        res[u_key] = item;
    }
  });
  return Object.values(res);
};

console.log(update(data));


推荐阅读