比较JavaScript中的三个数组

时间:2018-09-17 07:34:28

标签: javascript

这是我的代码

const obj1 = [{ext: '1287',ip: '(Unspecified)',queue: []}];
const obj2 = [{Queue: '222',Members: [{"ext":"1287"},{"ext":"4118"}],Callers: []},{Queue: '111',Members: [{"ext":"4131"},{"ext":"1287"},{"ext":"4138"}],Callers: []}];

const hasExt = ext => o2 => o2.Members.some(m => m.ext === ext)

const result = obj1.map(o1 => {
  const newQueue = obj2
    .filter(hasExt(o1.ext))
    .map(m => m.Queue);

  return { ...o1, queue: [...o1.queue, ...newQueue] };
})

console.log(result);

这是我的js小提琴https://jsfiddle.net/pravinnavle/myzsvbLr/1/ 在以上部分中,我将比较obj1和obj2。如果obj1的ext键的值与obj2的嵌套Members数组的ext键匹配,则obj2的Queue键的值将被推送到obj1中的队列数组。输出如下:

[
  {
    "ext": "1287",
    "ip": "(Unspecified)",
    "queue": [
      "222",
      "111"
    ]
  }
]

现在我有第三个这样的数组obj3

const obj3 = [{ ext: '1287',Prio: '1',State: 'Up'},{ ext: '1184',Prio: '1',State: 'Down'}]

我想比较obj1和obj3。如果obj1中的ext键的值与obj3中的ext键的值匹配,则应将obj3的Prio和State键推入obj1中的calls数组,并且最终数组应如下所示。

[
  {
    "ext": "1287",
    "ip": "(Unspecified)",
    "queue": [
      "222",
      "111"
    ],
    "calls": [
      {
      "Prio" : 1,
      "State" : "Up",
      }
    ],
  }
]

我无法将obj1与obj3进行比较,并以开头的代码中存在的结果常量输出它。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您可以尝试类似的事情。

const obj2 = [{
        "ext": "1287",
        "ip": "(Unspecified)",
        "queue": [
            "222",
            "111"
        ]
    }
];

const obj3 = [{ ext: '1287',Prio: '1',State: 'Up'},{ ext: '1184',Prio: '1',State: 'Down'}];

const func = (obj1, obj2) => {
    obj1.forEach((a) =>
      obj2.forEach((b) => {
        if (b.ext === a.ext) a.calls = (a.calls || []).concat(Object.assign({}, { Prio: b.Prio, State: b.State }));
      })
    );
};

func(obj2, obj3);

console.log(obj2);