首页 > 解决方案 > 如何使用js比较数组并创建最终数组?

问题描述

我有两个对象数组:

对象 1:

    [  
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Chest",
      "tech":"Embroidery"
   },
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Chest",
      "tech":"Screenprint Textile"
   },
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Arm Left",
      "tech":"Embroidery"
   },
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Arm Left",
      "tech":"Screenprint Textile"
   }
]

对象 2:[
{
"sku":"30772", "qty":"1" }, {
"position":"Position Arm Left", "tech":"刺绣" }, {
"position":"Position Chest ", "tech":"Screenprint Textile" } ]

对象 2:

[  
   {  
      "position":"Position Arm Left",
      "tech":"Embroidery"
   },
   {  
      "position":"Position Chest",
      "tech":"Screenprint Textile"
   }
]

我需要比较对象参数,即位置和技术,并需要获得最终数组,其中该位置和对象可用,如下所示

最终输出:

[  

   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Chest",
      "tech":"Screenprint Textile"
   },
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Arm Left",
      "tech":"Embroidery"
   }
]

标签: javascriptarraysjsonobjectcompare

解决方案


如果你使用 lodash 那么你可以使用intersectionWith方法,因为你想要基于两个键的交叉是直观的。

const object1 = [
  {
    id: "30772",
    posimage: "/b/l/blue-shirt_1_1.jpg",
    position: "Position Chest",
    tech: "Embroidery"
  },
  {
    id: "30772",
    posimage: "/b/l/blue-shirt_1_1.jpg",
    position: "Position Chest",
    tech: "Screenprint Textile"
  },
  {
    id: "30772",
    posimage: "/b/l/blue-shirt_1_1.jpg",
    position: "Position Arm Left",
    tech: "Embroidery"
  },
  {
    id: "30772",
    posimage: "/b/l/blue-shirt_1_1.jpg",
    position: "Position Arm Left",
    tech: "Screenprint Textile"
  }
];

const object2 = [
  {
    position: "Position Arm Left",
    tech: "Embroidery"
  },
  {
    position: "Position Chest",
    tech: "Screenprint Textile"
  }
];

const result = _.intersectionWith(
  object1,
  object2,
  (o1, o2) => o1.position === o2.position && o1.tech === o2.tech
);

console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>


推荐阅读