javascript - 如何根据2个键获取不同的数组列表?

标签 javascript arrays

我有以下 2 个数组。

const array1 = [
    {name: "V1", year: "2018", isDefault: false},
    {name: "V2", year: "2018", isDefault: false},
    {name: "V3", year: "2018", isDefault: false},
    {name: "V4", year: "2018", isDefault: false},
    {name: "V1", year: "2019", isDefault: true}
  ];

const array2 = [
    {name: "V1", year: "2018", isDefault: false},
    {name: "V2", year: "2018", isDefault: false},
    {name: "V3", year: "2018", isDefault: false},
    {name: "V4", year: "2018", isDefault: false},
    {name: "V1", year: "2020", isDefault: true}
  ];

我想要得到一个结果数组,其中包含 array1 和 array2 中的所有项目,但基于名称和年份(基于 2 个键的组合)仅包含一次公共(public)项目。我必须按如下方式获取结果数组:

const array = [
    {name: "V1", year: "2018", isDefault: false},
    {name: "V2", year: "2018", isDefault: false},
    {name: "V3", year: "2018", isDefault: false},
    {name: "V4", year: "2018", isDefault: false},
    {name: "V1", year: "2019", isDefault: true},
    {name: "V1", year: "2020", isDefault: true}
  ];

请帮助我如何在 javascript 中获取它?

最佳答案

您可以将 array2 的过滤版本连接到 array1

const array1 = [
    {name: "V1", year: "2018", isDefault: false},
    {name: "V2", year: "2018", isDefault: false},
    {name: "V3", year: "2018", isDefault: false},
    {name: "V4", year: "2018", isDefault: false},
    {name: "V1", year: "2019", isDefault: true}
];

const array2 = [
    {name: "V1", year: "2018", isDefault: false},
    {name: "V2", year: "2018", isDefault: false},
    {name: "V3", year: "2018", isDefault: false},
    {name: "V4", year: "2018", isDefault: false},
    {name: "V1", year: "2020", isDefault: true}
];

let res = array1.concat(
    array2.filter(({name, year}) => !array1.some(y => y.name === name && y.year === year))
);

console.log(res);

关于javascript - 如何根据2个键获取不同的数组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54169850/

相关文章:

javascript - Angular 6 - 表单 - 选择选项未正确更新

javascript - 从键和值是动态的数组中搜索字符串

javascript - 什么是 javascript monorepo 的正确方法

javascript - 在javascript中创建一个累积和数组

c - C 中的动态内存分配 : Problems in Realloc

javascript - 使用 Underscore.js 从对象中删除空属性/虚假值

arrays - Excel VBA 编译错误参数在遍历附加到类集合的数组时不是可选的

javascript - 无法从 promise 中捕获异常

javascript - Jquery点击失败

javascript - 如何在数组中选择随机元素避免(如果是的话除外)某个值?