如何通过相同的值和某些属性来联合/分组对象数组?

时间:2016-05-31 14:27:02

标签: javascript underscore.js

我有一些数组:

[
  {
    billable: 1,
    source: "Facebook",
    providerAccountId: 5,
    message_id: "5bb1a457"
  },
  {
    billable: 1,
    source: "Facebook",
    providerAccountId: 5,
    message_id: "6bb3G465"
  },
  {
    destination: "8801856472841"
    message_id: "5bb1a457"
  }
]

//after union, i need to get result:
 
[
  {
    billable: 1,
    source: "Facebook",
    providerAccountId: 5,
    message_id: "5bb1a457"
    destination: "8801856472841"
  },
  {
    billable: 1,
    source: "Facebook",
    providerAccountId: 5,
    message_id: "6bb3G465"
  }
]

请帮助,myabe是否可能通过具有独特价值的财产进行分组或结合。只是通过指定的peoperty和缺少的属性将具有相同值的所有对象连接到连接对象

2 个答案:

答案 0 :(得分:1)

您可以循环遍历数组并在应用已插入对象的属性时对其进行过滤。

此提议使用(真正的)空对象作为对已过滤对象的引用的哈希表。如果存在具有相同message_id的对象,则将实际对象的所有属性分配给具有散列的对象。



var array = [{ billable: 1, source: "Facebook", providerAccountId: 5, message_id: "5bb1a457" }, { billable: 1, source: "Facebook", providerAccountId: 5, message_id: "6bb3G465" }, { destination: "8801856472841", message_id: "5bb1a457" }];

array = array.filter(function (a) {
    if (!this[a.message_id]) {
        this[a.message_id] = a;
        return true;
    }
    Object.keys(a).forEach(function (k) {
        this[k] = a[k];
    }, this[a.message_id]);
}, Object.create(null));

console.log(array);




答案 1 :(得分:1)

您可以通过要检查的密钥对其进行映射,并最终将其合并:

# Load static web resources from different directory.
#
# This setting is dependent on application server plugin(Jetty, Tomcat, JBoss, ...)
webappDir=/dev/workspace/myapp_web/WebContent/