首页 > 解决方案 > 合并对象数组并获取唯一值

问题描述

我有两个包含嵌套对象的数组。我想合并这些并获得一个独特的数组

我有这两个数组

// 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

谢谢!

标签: javascriptarraysobject

解决方案


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


推荐阅读