如何使用javascript或jquery或angularjs为所选键添加JSON值?

时间:2016-10-22 19:01:16

标签: javascript jquery angularjs json

我有以下json

var json = var data = [{
    "a": 150
}, {
    "a": 50
}, {
    "b": 100
}, {
    "b": 25
}];

我想添加" a"的值和" b"在我的finaljson(它是我想要的输出json)中,例如:

var finaljson = [{
    "a": 200
}, {
    "b": 125
}];

如何使用finaljsonjsonjavascript获取给定jquery内容的上述angularjs结果结构?

请注意,此处finaljson应添加上述" a"价值和" b"值如:a: 150+50=200, b: 100+25=125

请提前通知我,并提前致谢。创建了Fiddle

4 个答案:

答案 0 :(得分:1)

var json = [{
    "a": 150
}, {
    "a": 50
}, {
    "b": 100
}, {
    "b": 25
}];

 var finaljson = [];
 var a= json[0].a+json[1].a;
 var b= json[2].b+json[3].b;
 finaljson.push(a);
  finaljson.push(b);
  console.log(finaljson);

答案 1 :(得分:1)

这个解决方案怎么样?

const json = [
  { "a": 150 }, 
  { "a": 50  }, 
  { "b": 100 }, 
  { "b": 25  }
];

const reduce = (data) => 
  data.reduce((acc, obj) => {
    for(const i in obj){
      acc[i] = (acc[i] || 0) + obj[i];
    }
    return acc;
  }, {})
;

reduce(json);

将输出

{
    "a": 200,
    "b": 125
}

答案 2 :(得分:1)

您可以使用哈希表作为对相同键的结果的引用。

var data = [{ "a": 150 }, { "a": 50 }, { "b": 100 }, { "b": 25 }],
    result = data.reduce(function (hash) {
        return function (r, a) {
            var key = Object.keys(a)[0],
                o = {};

            if (!hash[key]) {
                o[key] = 0;
                hash[key] = o;
                r.push(o);
            }
            hash[key][key] += a[key];
            return r;
        };
    }(Object.create(null)), []);

console.log(result);

ES6与Map

var data = [{ "a": 150 }, { "a": 50 }, { "b": 100 }, { "b": 25 }],
    result = data.reduce((map => (r, a) => {
        var key = Object.keys(a)[0];
        if (!map.has(key)) {
            map.set(key, { [key]: 0 });
            r.push(map.get(key));
        }
        map.get(key)[key] += a[key];
        return r;
    })(new Map), []);

console.log(result);

答案 3 :(得分:1)

let json = [   
    { "a": 150 },
    { "a": 50  },
    { "b": 100 },
    { "b": 25  } 
];

let sumSameProperties = function (json) {
    let middleJson = [];
    for (let i = 0; i < json.length; ++i) {
        let keys = Object.keys(json[i]);
        for (let k = 0; k < keys.length; ++k) { 
            if(!isNaN(middleJson[keys[k]])){
                middleJson[keys[k]] += json[i][keys[k]];
            }else {
                middleJson[keys[k]] = json[i][keys[k]];
            }
        }
    }
    return middleJson;
};
let finalJson = [];
let almostThere = sumSameProperties(json);
for (let key in almostThere) {
    let obj = {};
    obj[key] = almostThere[key];
    finalJson.push(obj);
}
console.log(finalJson);