我有两个或多个JavaScript对象。我想合并它们,添加共同属性的值,然后按值的降序对其进行排序。
例如
var a = {en : 5,fr: 3,in: 9} var b = {en: 8,fr: 21,br: 8} var c = merge(a,b)
c 然后应该是这样的:
c
c = { fr: 24, en: 13, in:9, br:8 }
即,两个对象都合并,添加共同键的值,然后对键进行排序。
这是我尝试过的:
var a = {en : 5,fr: 3,in: 9} var b = {en: 8,fr: 21,br: 8} c = {} // copy common values and all values of a to c for(var k in a){ if(typeof b[k] != 'undefined'){ c[k] = a[k] + b[k] } else{ c[k] = a[k]} } // copy remaining values of b (which were not common) for(var k in b){ if(typeof c[k]== 'undefined'){ c[k] = b[k] } } // Create a object array for sorting var arr = []; for(var k in c){ arr.push({lang:k,count:c[k]}) } // Sort object array arr.sort(function(a, b) { return b.count - a.count; })
但我认为它没有好处。如此多的循环:(如果有人可以提供更少混乱且良好的代码,那就太好了。
无法对对象的属性进行排序,但是可以对数组进行排序:
var merged = $.extend({}, a); for (var prop in b) { if (merged[prop]) merged[prop] += b[prop]; else merged[prop] = b[prop]; } // Returning merged at this point will give you a merged object with properties summed, but not ordered. var properties = []; for (var prop in merged) { properties.push({ name: prop, value: merged[prop] }); } return properties.sort(function(nvp1, nvp2) { return nvp1.value - nvp2.value; });