从对象数组中删除重复的键

时间:2018-12-10 14:30:55

标签: javascript arrays javascript-objects reduce

我有一个这样的对象数组

let array = [
  {
    sector: "adad"
  },
  {
    sector: "adadasdsd"
  },
  {
    sector: "sdsdsd"
  },
  {
    origin: "sdfsf"
  },
  {
    destination: "dfsfsdf"
  }
];

我希望它像这样:

let array = [
  { sector: ["adad", "adadasdsd", "sdsdsd"] },
  { origin: ["sdfsf"] },
  { destination: ["dfsfsdf"] }
];

让我知道如何实现。我知道减少会帮助我。但是我坚持如何进行呢?有帮助吗?

6 个答案:

答案 0 :(得分:4)

您可以使用哈希表来收集相同键的值,然后再映射到单个键/值对。

let array = [{ sector: "adad" }, { sector: "adadasdsd" }, { sector: "sdsdsd" }, { origin: "sdfsf" }, { destination: "dfsfsdf" }],
    grouped = Object
        .entries(array.reduce(
            (r, o) => (
                Object.entries(o).forEach(([k, v]) => (r[k] = r[k] || []).push(v)),
                r
            ),
            Object.create(null)
        ))
        .map(([k, v]) => ({ [k]: v }));
   
console.log(grouped);

答案 1 :(得分:0)

您可以尝试使用jQuery

let array2 = {
        sector: [],
        origin: [],
        destination: []
    }


$.each(array, function (_index, value) {
    if (value.sector != null)
        array2.sector.push(value.sector)
    if (value.origin != null)
        array2.origin.push(value.origin)
    if (value.destination != null)
        array2.destination.push(value.destination)
})

答案 2 :(得分:0)

具有减少作用的香草溶液:

packets

答案 3 :(得分:0)

使用Array.prototype.reduce()的常规解决方案:

let array =   [{"sector": "adad"},{"sector": "adadasdsd"},{"sector": "sdsdsd"},{"origin": "sdfsf"},{"destination":"dfsfsdf"}]

let reduced = array.reduce((a, c, i) => {
  let key = Object.keys(c)[0];
  if (!(key in a)) a[key] = [];
  if (!a[key].includes(c[key])) a[key].push(c[key]);
  return a;
}, {})

console.log(reduced)

答案 4 :(得分:0)

这里是一种方法:

let array =   [
  {
    "sector": "adad"
  },
  {
    "sector": "adadasdsd"
  },
  {
    "sector": "sdsdsd"
  },
  {
    "origin": "sdfsf"
  },
  {
    "destination": "dfsfsdf"
  }
]

let res = [];
array.map(item=>{
  let key = Object.keys(item)[0], value = item[key],
      objRes = res.filter(r=>r[key]);  
  if (objRes.length == 0) {
      let obj = {};
      obj[key] = [value];
      res.push(obj);
  } else 
      objRes[0][key].push(value);
});

console.log(res);

答案 5 :(得分:0)

如果您使用Array.reduceMap作为累加器,则可以以一种简洁的方式解决此问题:

let array = [{ sector: "adad" }, { sector: "adadasdsd" }, { sector: "sdsdsd" }, { origin: "sdfsf" }, { destination: "dfsfsdf" } ];

const result = array.reduce((m, c, i, a) => {
  Object.keys(c).forEach(key => m.set(key, [...(m.get(key)||[]), c[key]]))
  return i == a.length - 1 ? Array.from(m, ([k,v]) => ({[k]: v}))  : m
}, new Map())

console.log(result)