javascript - 根据特定值识别数组中的唯一对象
问题描述
我有以下对象数组,我需要根据 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'}]
根据评论中的问题为问题添加更多颜色。
img1
key 具有我需要从中找到唯一值的值,然后img2
从第一个匹配项中找到 key 的相应值。
非常感谢您的帮助!
解决方案
使用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));
推荐阅读
- vue.js - 将插槽嵌套在 vue 的插槽中
- c# - 如何从数组中删除一个元素并将其余元素移回?(C#)
- linux - 含义警告“文件被多个包触及”
- python - Python,命名元组,扩展制作基本零件库存系统
- reactjs - React 应用程序在通过 safari 访问时会抛出 401 错误,但其他情况下不会
- javascript - 将每个返回的对象推入数组 React
- c# - 如何优化我的代码以并行运行每个提取
- ios - 如果 index.row 在我的数组中,则为单元格设置图像
- javascript - create-react-app/react-native-elements 错误
- c# - 有没有办法将字典对的值传递给 C# 中的变量?