javascript - 合并对象数组并获取唯一值
问题描述
我有两个包含嵌套对象的数组。我想合并这些并获得一个独特的数组
我有这两个数组
// ARRAY 1
let variants = [
{color: "Red", sizes: "Small", material: "Cotton", price: "$100", ...},
{color: "Red", sizes: "Large", material: "Cotton", price: "$120", ...},
{color: "Blue", sizes: "Small", material: "Cotton", price: "$150", ...},
{color: "Blue", sizes: "Large", material: "Cotton", price: "$180", ...},
]
// ARRAY 2
let newVariants = [
{color: "Red", sizes: "Small", material: "Cotton"}, // this one is already exist in ARRAY 1
{color: "Red", sizes: "Large", material: "Cotton"}, // this one is already exist in ARRAY 1
{color: "Blue", sizes: "Small", material: "Cotton"}, // this one is already exist in ARRAY 1
{color: "Blue", sizes: "Large", material: "Wool"}, // this one is new object
{color: "Green", sizes: "Large", material: "Cotton"}, // this one is new object
]
我想要这个
[
{color: "Red", sizes: "Small", material: "Cotton", price: "$100"},
{color: "Red", sizes: "Large", material: "Cotton", price: "$120"},
{color: "Blue", sizes: "Small", material: "Cotton", price: "$150"},
{color: "Blue", sizes: "Large", material: "Cotton", price: "$180"},
{color: "Blue", sizes: "Large", material: "Wool", price: null, ...},
{color: "Green", sizes: "Large", material: "Cotton", price: null, ...}
]
注意:ARRAY 1 的值将始终取代 ARRAY 2
谢谢!
解决方案
ARRAY 1 的值将始终取代 ARRAY 2
您可以使用以下过滤器进行.filter
过滤.some
:
let variants = [ {color: "Red", sizes: "Small", material: "Cotton", price: "$100",}, {color: "Red", sizes: "Large", material: "Cotton", price: "$120",}, {color: "Blue", sizes: "Small", material: "Cotton", price: "$150",}, {color: "Blue", sizes: "Large", material: "Cotton", price: "$180",}, ];
let newVariants = [ {color: "Red", sizes: "Small", material: "Cotton"}, {color: "Red", sizes: "Large", material: "Cotton"}, {color: "Blue", sizes: "Small", material: "Cotton"}, {color: "Blue", sizes: "Large", material: "Wool"}, {color: "Green", sizes: "Large", material: "Cotton"}, ];
const isEqual = (p1, p2) => p1.color == p2.color && p1.sizes == p2.sizes && p1.material == p2.material;
const filteredExtraVariants = newVariants.filter(p1 => !variants.some(p2 => isEqual(p1, p2)));
const extraVariants = filteredExtraVariants.map(r =>
{
r.price = null;
return r;
});
const result = variants.concat(extraVariants);
console.log(result);
推荐阅读
- php - 需要更改数组的行数
- python - 在 biopython 中仅显示 dna 对齐分数
- java - 我的应用程序在我的 android 模拟器上运行,但在我的真实移动设备上运行不正常
- javascript - 如何定义“公会”?
- powerbi - 基于另一个表的条件计算总和的 DAX 语法
- java - 我可以将 Firebase 与 java 桌面应用程序一起使用吗?
- python - 数据框应用(映射)函数类型错误
- sql - 在 SQL Server 插入命令期间,字符串或二进制数据将被截断消息
- php - 使用 FOSUserBundle 进行 Google+ 身份验证
- java - 通过反射从类的变量中获取值,然后使用值的方法