合并两个javascript对象,添加通用属性值 [英] Merge two javascript objects adding values of common properties

查看:70
本文介绍了合并两个javascript对象,添加通用属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个或多个javascript对象.我想合并它们,添加通用属性的值,然后按值的降序对其进行排序.

I have two or more javascript objects. I want to merge them adding values of common properties and then sort them in descending order of values.

例如

var a = {en : 5,fr: 3,in: 9}
var b = {en: 8,fr: 21,br: 8}

var c = merge(a,b)

c然后应该像这样:

c = {
fr: 24,
en: 13,
in:9,
br:8
} 

即将这两个对象合并,添加共同键的值,然后对键进行排序.

i.e. both objects are merge, values of common keys are added and then keys are sorted.

这是我尝试过的:

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;
})

但是我不认为这很好.如此之多的循环:(如果有人可以提供少一些混乱且良好的代码,那就太好了.

but I dont think its good. So many loops :( It would be nice if someone can provide a less messy and good code.

推荐答案

无法对对象的属性进行排序,但是可以对数组进行排序:

It is not possible to sort the properties of an object, you can however sort an array:

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;
});

这篇关于合并两个javascript对象,添加通用属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆