使用jQuery(JavaScript)合并对象数组中多个相同键的值

时间:2017-08-17 13:02:20

标签: javascript arrays object associative-array

合并这样一个对象数组的优雅方式(jQuery或JavaScript):

var params = [
 {"name":"filter_color","value":"black"},
 {"name":"filter_color","value":"blue"},
 {"name":"filter_size","value":"l"},
 {"name":"filter_size","value":"m"}
];

成:

var params = [
 {"name":"filter_color","value":"black,blue"},
 {"name":"filter_size","value":"l,m"}
]

以后用于$ .param(params)?

2 个答案:

答案 0 :(得分:1)

您可以使用哈希表并按所需密钥对其进行分组。

function groupBy(array, key, fn) {
    var hash = Object.create(null);
    return array.reduce(function (r, o) {
        if (!hash[o[key]]) {
            hash[o[key]] = {};
            hash[o[key]][key] = o[key];
            r.push(hash[o[key]]);
        }
        fn(o, hash[o[key]]);
        return r;
    }, []);
}

var array = [{ name: "filter_color", value: "black" }, { name: "filter_color", value: "blue" }, { name: "filter_size", value: "l" }, { name: "filter_size", value: "m" }],
    result = groupBy(array, 'name', function (s, t) {
        t.value = t.value ? t.value + ',' + s.value : s.value;
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

您可以使用Array.reduce方法将现有的array转换为新结构。

let arr = [
 {"name":"filter_color","value":"black"},
 {"name":"filter_color","value":"blue"},
 {"name":"filter_size","value":"l"},
 {"name":"filter_size","value":"m"}
];

let newArr = arr.reduce((acc, curr) => {
  if(acc.some(obj => obj.name === curr.name)) {
    acc.forEach(obj => {
      if(obj.name === curr.name) {
        obj.value = obj.value + " " + curr.value;
      }
    });
  } else {
    acc.push(curr);
  }
  return acc;
}, []);

console.log(newArr);