我有一组具有相同属性和不同属性值的对象。
var arr = [{
1: ["option1", "option2"],
2: ["option2"],
3: ["option1"]
}, {
1: ["option2", "option1"],
2: ["option1"],
3: ["option1"]
}];
我想计算每个属性(在所有对象中都是相同的)的值出现,所以我需要以某种方式合并这些对象,或者可能以其他方式进行比较。
这里的伙计帮助我通过使用嵌套循环How to compare and count instances of several objects' property values placed in array in javascript?
来迭代它但是,我不确定它能否解决问题。使用下面的代码,我仍然无法弄清楚如何将每个对象的属性值合并到一个对象中,以便属性匹配。请帮忙。
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
for (var key in obj) {
if (obj.hasOwnProperty(key)) { // skip properties inherited from prototype
var arr2 = obj[key];
for (var j = 0; j < arr2.length; j++) {
// Do something with arr2[j]
}
}
}
}
结果结构是
{
1: {
option1: 2,
option2: 2
},
2: {
option2: 1,
option1: 1
},
3: {
option1: 2
}
}
答案 0 :(得分:0)
var count = {};
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var arr2 = obj[key];
for (var j = 0; j < arr2.length; j++) {
count[arr2[j]] = (count[arr2[j]] || 0) + 1;
}
}
}
}
产地:
{
option1: 5,
option2: 3
}
var count = [];
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
count[i] = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var arr2 = obj[key];
for (var j = 0; j < arr2.length; j++) {
count[i][arr2[j]] = (count[i][arr2[j]] || 0) + 1;
}
}
}
}
产地:
[
{
option1: 2,
option2: 2
},{
option2: 1,
option1: 3
}
]
var count = {};
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if(!count[key]) count[key] = {};
var arr2 = obj[key];
for (var j = 0; j < arr2.length; j++) {
count[key][arr2[j]] = (count[key][arr2[j]] || 0) + 1;
}
}
}
}
产地:
{
1: {
option1: 2,
option2: 2
},
2: {
option2: 1,
option1: 1
},
3: {
option1: 2
}
}
答案 1 :(得分:0)
这是我如何做到这一点,使用下划线并牺牲一些效率,试图让它更具可读性(总是很难跟上嵌套3层深度的循环):
(下划线文档位于http://underscorejs.org/)
var arr = [{
1: ["option1", "option2"],
2: ["option2"],
3: ["option1"]
}, {
1: ["option2", "option1"],
2: ["option1"],
3: ["option1"]
}];
var counts = {};
var flattened = _.map(arr, function(item, index) {
index++;
counts[index] = {};
var values = _.flatten(_.values(item));
_.each(values, function(val) {
counts[index][val] = (counts[val] || 0) + 1;
});
return counts;
});
console.log(JSON.stringify(counts));
// prints: [{"1":{"option1":1,"option2":1},"2":{"option2":1,"option1":1}},{"1":{"option1":1,"option2":1},"2":{"option2":1,"option1":1}}]
相关的jsfiddle:http://jsfiddle.net/8yx6P/3/