在JavaScript中迭代一系列对象

时间:2014-11-29 10:07:37

标签: javascript for-loop

我有一个对象数组,如下所示:

var model = ([{ "MKT_BRAND_NAME": "LUX", "Brand_GRP": 783.52, "Category_GRP": 0.0, "SOV": 0.051, "MM": "10", "QUARTER": "", "YYYY": "2014", "TargetGroupId": null  },
           { "MKT_BRAND_NAME": "LUX", "Brand_GRP": 356.12, "Category_GRP": 0.0, "SOV": 0.050, "MM": "11", "QUARTER": "", "YYYY": "2014", "TargetGroupId": null },
           { "MKT_BRAND_NAME": "LUX", "Brand_GRP": 935.27, "Category_GRP": 0.0, "SOV": 0.23, "MM": "7 ", "QUARTER": "", "YYYY": "2014", "TargetGroupId": null},
           { "MKT_BRAND_NAME": "LUX", "Brand_GRP": 3380.81, "Category_GRP": 0.0, "SOV": 0.15, "MM": "8 ", "QUARTER": "", "YYYY": "2014", "TargetGroupId": null },
           { "MKT_BRAND_NAME": "LUX", "Brand_GRP": 3536.21, "Category_GRP": 0.0, "SOV": 0.15, "MM": "9 ", "QUARTER": "", "YYYY": "2014", "TargetGroupId": null}
           { "MKT_BRAND_NAME": "PEARS", "Brand_GRP": 3380.81, "Category_GRP": 0.0, "SOV": 0.18, "MM": "8 ", "QUARTER": "", "YYYY": "2014", "TargetGroupId": null },
           { "MKT_BRAND_NAME": "PEARS", "Brand_GRP": 3536.21, "Category_GRP": 0.0, "SOV": 0.17, "MM": "9 ", "QUARTER": "", "YYYY": "2014", "TargetGroupId": null}]);

我想显示特定MKT_BRAND_NAME的SOV和MM值。我想将MKT_BRAND_NAME分配给“密钥”,将MM和SOV分配给“值”。这样的东西

  var model = [{
            "key": "Lux",
            "values": [{MM:"10",SOV:0.015},
                       {MM:"11",SOV:0.050},
                       {MM:"7",SOV:0.23},
                       {MM:"8",SOV:0.15},
                       {MM:"9",SOV:0.15}]
                    }, {
           "key": "Pears",
           "values": [{MM:"8",SOV:0.018},
                      {MM:"9",SOV:0.017},

        }];

任何人都可以通过for中的JavaScript循环告诉我如何实现这一目标。

2 个答案:

答案 0 :(得分:2)

此功能可以满足您的需求:

function convert(model) {
    var new_model = [];
    for (var i = 0; i < model.length; i++) {
        var model_record = model[i];
        var matched_new_model_record = null;
        for (var j = 0; j < new_model.length; j++) {
            var new_model_record = new_model[j];
            if (new_model_record.key === model_record.MKT_BRAND_NAME) {
                matched_new_model_record = new_model_record;
                break;
            }
        }
        if (matched_new_model_record === null) {
            matched_new_model_record = {key: model_record.MKT_BRAND_NAME, values: []};
            new_model.push(matched_new_model_record);
        }
        matched_new_model_record.values.push({MM: model_record.MM, SOV: model_record.SOV});
    }
    return new_model;
}

答案 1 :(得分:0)

如何使用reduce函数:

grouped = model.reduce(function(memo, o){

  if (typeof(memo[o["MKT_BRAND_NAME"]]) == "undefined")
    memo[o["MKT_BRAND_NAME"]] = [];

  memo[o["MKT_BRAND_NAME"]].push({MM: o["MM"], SOV: o["SOV"]});

  return memo;

}, {});

result = [];
for (var key in grouped) {
  result.push({key: key, values: grouped[key]})
}

console.log(JSON.stringify(result, null, 4))