两个对象数组:使用相同的键合并

时间:2019-08-09 17:04:52

标签: javascript

我有两个对象数组。我想将键与值合并

var a = [{"fit":["34","32","30","28"],"size":["x"]}]

var b = [{"size":["s","m","xl"],"fit":["36"]}]

预期输出应为

Obj=[{"fit":["34","32","30","28","36"],"size":["x,"s","m","xl"]}]

我的代码是

let arr3 = [];

b.forEach((itm, i) => {
  arr3.push(Object.assign({}, itm, a[i]));
});

alert(JSON.stringify(arr3))

it gives [{"size":["x"],"fit":["34","32","30","28"]}] which wrong.

4 个答案:

答案 0 :(得分:1)

ab合并到一个数组中,然后从具有空fitsize数组的对象的数组开始减少它:

var a = [{ fit: ["34", "32", "30", "28"], size: ["x"] }];

var b = [{ size: ["s", "m", "xl"], fit: ["36"] }];

var obj = [...a, ...b].reduce(
  (acc, curr) => {
    Object.keys(curr).forEach(k => {
      acc[0][k] = [...new Set([...(acc[0][k] || []), ...curr[k]])];
    });

    return acc;
  },
  [{}]
);

console.log(obj);

答案 1 :(得分:1)

使用Array.reduce()

// Combine into single array (spread operator makes this nice)
const myArray = [...a, ...b];

// "reduce" values in array down to a single object
const reducedArray = myArray.reduce((acc, val) => {
  return [{fit: [...acc.fit, ...val.fit], size: [...acc.size, ...val.size]}];
});

编辑:如果您希望化简器合并对象而不管其具有什么键和字段,则可以通过迭代对象的键并动态合并它们来完成:

const reducedArray = myArray.reduce((acc, val) => {
  const returnObject = {};
  for (const eaKey in acc) {
    returnObject[eaKey] = [...acc[eaKey], ...val[eaKey]];
  }
  return [returnObject];
});

如果对象的字段不是保证键,那么您将需要更加动态地检测合并的类型以及如何进行合并,但是有可能,我将其保留为练习供您确定出来。 :)

请注意,如果“ fit”和“ size”数组中的每个数组中都有重复的值,则不会对它们进行重复数据删除。您必须作为一个单独的步骤手动执行此操作,或者在reduce函数中或之后添加额外的逻辑。

答案 2 :(得分:0)

您可以创建一个combine函数,该函数从任意两个对象中提取fitsize并将其合并。

将其用作归并所有内容的简化器。

let combine = ({fit, size}, {fit: fit2, size: size2}) => 
    ({ fit: [...fit, ...fit2], size: [...size, ...size2] });

let result = [...a, ...b].reduce(combine);

示例:

var a = [{"fit":["34","32","30","28"],"size":["x"]}, {"fit": ["10", "11"], "size":["xxxxxxxxl"]}]

var b = [{"size":["s","m","xl"],"fit":["36"]}];
let combine = ({fit, size}, {fit: fit2, size: size2}) => 
({ fit: [...fit, ...fit2], size: [...size, ...size2] });

let result = [...a, ...b].reduce(combine);


console.log(result);

答案 3 :(得分:0)

如果您不想直接使用按键,可以尝试

const arr3 = b.reduce((carry, current, index) => {
    Object.keys(current)
    .forEach(key => {
       Object.assign(carry, { [key]: Array.prototype.concat.call(current[key], a[index][key])});
    });
    return carry;
}, {});