简体   繁体   English

排序和处理json对象,javascript

[英]sorting and manipulating json objects , javascript

I have a json response in the form : 我有一个json响应形式:

some_array = [{
ios: "110"
rate_pl: "PlanC"
ref_site: "N/A"
reservation_id: "12709034"
},{
ios: "121"
rate_pl: "SomePlan"
ref_site: "FB"
reservation_id: "1273034
},{
ios: "141"
rate_pl: "PlanC"
ref_site: "Tweet"
reservation_id: "143034
}];

How do i group a particular attribute say 'rate_pl' and also add the values if the ios which related to that particular rate_pl. 我如何将特定属性分组为“ rate_pl”,如果与该特定rate_pl相关的ios也要添加值。

example --> Result should be: 示例->结果应为:

someObject = [
    {PlanC: ['ios':251]},              //(110+141 = 251)
    {SomePlan: ['ios':121]}
    ]; 

You could use reduce function, like this: 您可以使用reduce函数,如下所示:

var result = some_array.reduce(function(prev, cur) {
    if (prev[cur.rate_pl] === undefined) {        
        prev[cur.rate_pl] = [];
        prev[cur.rate_pl].push({ ios : parseInt(cur.ios, 10) });
    } else {
        prev[cur.rate_pl][0].ios += parseInt(cur.ios, 10);
    }
    return prev;
}, []);

Little demo . 小样

As others have stated it is a bit confusing what you want since you are mixing arrays and objects. 正如其他人所说,由于要混合数组和对象,因此您想要的内容有些混乱。

Just to help you going, if you are looking for this response: 只是为了帮助您,如果您正在寻找此回复:

{
    PlanC: {
        ios: 251
    },
    SomePlan: {
        ios: 121
    }
}

You can use this code: 您可以使用以下代码:

var new_object = {};
for (var i = 0; i < some_array.length; i++) {
    if (angular.isUndefined(new_object[some_array[i].rate_pl])) {
        new_object[some_array[i].rate_pl] = {ios: 0};
    }
    new_object[some_array[i].rate_pl].ios += parseInt(some_array[i].ios);
}

If you actually want some of the objects to be arrays that should be easy to modify. 如果您实际上希望某些对象是数组,则应该易于修改。

The first thing to do is to group the array by rate_pl using _.groupBy : 首先要做的是使用_.groupBy通过rate_pl对数组进行分组

var groups = _.groupBy(some_array,'rate_pl')

This will return an object with the keys being the distinct rate_pl values and the values will be an array of all the objects having that rate_pl: 这将返回一个对象,其键是不同的rate_pl值,并且值将是所有具有该rate_pl的对象的数组:

{
   PlanC: [ { ios: '110', etc }, {iod: '141' etc } ],
   SomePlan: [ { ios: 121 etc } ]
}

The next thing to do is to transform the values into what you want (or something similar to what you want). 下一步是将值转换为所需的值(或类似于所需的值)。 This can be done using _.mapObject which was introduced in Underscore 1.8: 这可以使用Underscore 1.8中引入的_.mapObject来完成:

var result = _.mapObject(groups, function(rates){
    return {
        ios: _.reduce(rates, function(memo, rate){
            return memo + parseInt(rate.ios);
        }, 0)
    }
});

This will give you: 这将为您提供:

{
   PlanC: { ios: '251' },
   SomePlan: { ios: 121 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM