使用相同的键合并数组中的 JavaScript 对象

IT技术 javascript arrays
2021-01-20 19:41:05

从共享一个键的 JavaScript 对象合并数组内容的最佳方法是什么?

如何才能array在下面的例子中被改组为output在这里,所有value键(无论是否为数组)都合并到共享相同name键的所有对象中

var array = [
    {
        name: "foo1",
        value: "val1"
    }, {
        name: "foo1",
        value: [
            "val2",
            "val3"
        ]
    }, {
        name: "foo2",
        value: "val4"
    }
];

var output = [
    {
        name: "foo1",
        value: [
            "val1",
            "val2",
            "val3"
        ]
    }, {
        name: "foo2",
        value: [
            "val4"
        ]
    }
];
6个回答

这是一种选择:-

var array = [{
  name: "foo1",
  value: "val1"
}, {
  name: "foo1",
  value: ["val2", "val3"]
}, {
  name: "foo2",
  value: "val4"
}];

var output = [];

array.forEach(function(item) {
  var existing = output.filter(function(v, i) {
    return v.name == item.name;
  });
  if (existing.length) {
    var existingIndex = output.indexOf(existing[0]);
    output[existingIndex].value = output[existingIndex].value.concat(item.value);
  } else {
    if (typeof item.value == 'string')
      item.value = [item.value];
    output.push(item);
  }
});

console.dir(output);

抱歉@ArpitMeena,现在才在评论中看到您的请求。我已将其更改为item将来有帮助。
2021-03-12 19:41:05
如果我有一个包含多个对象的数组都共享一个相同的键,但是这个键是未知的,例如对象结构之一是{ "127.0.0.1" : 1, "127.0.0.2" : 1, "127.0.0.3" : 1, "127.0.0.4" : 1, }第二个对象{ "127.0.0.1" : 1000, "127.0.0.2" : 1000, "127.0.0.3" : 1000, "127.0.0.4" : 1000, },如何合并它们以便输出,就像这样{"127.0.0.1": 1, "my-custom-key": 1000}, second obj etc....ps值可能不同我只是举了一个简单的例子。
2021-03-21 19:41:05
你是救命稻草!!
2021-03-22 19:41:05
keyvalue名字不一样。我很困惑,因为这里value输入对象中名称是value,而您在forEach循环中采用的参数名称也被命名为 value。请把我的困惑说清楚。谢谢。
2021-04-07 19:41:05

这是实现该目标的另一种方法:

var array = [{
  name: "foo1",
  value: "val1"
}, {
  name: "foo1",
  value: [
    "val2",
    "val3"
  ]
}, {
  name: "foo2",
  value: "val4"
}];

var output = array.reduce(function(o, cur) {

  // Get the index of the key-value pair.
  var occurs = o.reduce(function(n, item, i) {
    return (item.name === cur.name) ? i : n;
  }, -1);

  // If the name is found,
  if (occurs >= 0) {

    // append the current value to its list of values.
    o[occurs].value = o[occurs].value.concat(cur.value);

    // Otherwise,
  } else {

    // add the current item to o (but make sure the value is an array).
    var obj = {
      name: cur.name,
      value: [cur.value]
    };
    o = o.concat([obj]);
  }

  return o;
}, []);

console.log(output);

如果我需要将 vaue 添加为对象,该怎么办?
2021-04-08 19:41:05

使用lodash

var array = [{name:"foo1",value:"val1"},{name:"foo1",value:["val2","val3"]},{name:"foo2",value:"val4"}];

function mergeNames (arr) {
    return _.chain(arr).groupBy('name').mapValues(function (v) {
        return _.chain(v).pluck('value').flattenDeep();
    }).value();
}

console.log(mergeNames(array));
简化版,现在也 pluck 应该是 map : const mergeNames = arr => _.chain(arr).groupBy('name').mapValues(v => _.chain(v).map('value').flattenDeep()).value(); console.log(mergeNames(array));
2021-03-18 19:41:05
数据来自'2021-04-14':LodashWrapper { wrapped:LazyWrapper{ wrapped:[LodashWrapper], actions:[Array], dir:1, filtered:false, iteratees:[Array], takeCount:4294967295, views : [] }, actions : [ [Object] ], chain : true, index : 0, values : undefined } 这种格式。如何将其转换为数组格式?
2021-03-29 19:41:05

2021版

var arrays = [{ name: "foo1",value: "val1" }, {name: "foo1", value: ["val2", "val3"] }, {name: "foo2",value: "val4"}];

const result = arrays.reduce((acc, {name, value}) => {
  acc[name] ??= {name: name, value: []};
  if(Array.isArray(value)) // if it's array type then concat 
    acc[name].value = acc[name].value.concat(value);
  else
    acc[name].value.push(value);
  
  return acc;
}, {});

console.log(Object.values(result));

这是一个使用 ES6 Map 的版本:

const arrays = [{ name: "foo1",value: "val1" }, {name: "foo1", value: ["val2", "val3"] }, {name: "foo2",value: "val4"}];

const map = new Map(arrays.map(({name, value}) => [name, { name, value: [] }])); 
for (let {name, value} of arrays) map.get(name).value.push(...[value].flat());
console.log([...map.values()]);