创建一个新的对象数组,而不重复键值对

时间:2016-08-02 00:24:28

标签: javascript arrays javascript-objects

假设我有一系列对象:

var myData = [
 {"ccode":"AFG", "cname":"Afghanistan", "figure":"1", "year":"2012"},
 {"ccode":"AFG", "cname":"Afghanistan", "figure":"3", "year":"2013"},
 {"ccode":"AFG", "cname":"Afghanistan", "figure":"5", "year":"2014"},
 {"ccode":"AFG", "cname":"Afghanistan", "figure":"6", "year":"2015"},
 {"ccode":"AUS", "cname":"Australia", "figure":"6", "year":"2012"},
 {"ccode":"AUS", "cname":"Australia", "figure":"5", "year":"2013"},
 {"ccode":"AUS", "cname":"Australia", "figure":"7", "year":"2014"}
]

如何让他们成为:

var myNewData = [
 {"ccode":"AFG", "cname":"Afghanistan", "2012":"1", "2013":"3", "2014":"5", "2015":"6"},
 {"ccode":"AUS", "cname":"Australia", "2012":"6", "2013":"5", "2014":"7"}
]

2 个答案:

答案 0 :(得分:1)



var myData = [{
  "ccode": "AFG",
  "cname": "Afghanistan",
  "figure": "1",
  "year": "2012"
}, {
  "ccode": "AFG",
  "cname": "Afghanistan",
  "figure": "3",
  "year": "2013"
}, {
  "ccode": "AFG",
  "cname": "Afghanistan",
  "figure": "5",
  "year": "2014"
}, {
  "ccode": "AFG",
  "cname": "Afghanistan",
  "figure": "6",
  "year": "2015"
}, {
  "ccode": "AUS",
  "cname": "Australia",
  "figure": "6",
  "year": "2012"
}, {
  "ccode": "AUS",
  "cname": "Australia",
  "figure": "5",
  "year": "2013"
}, {
  "ccode": "AUS",
  "cname": "Australia",
  "figure": "7",
  "year": "2014"
}];

var i,len, res = [], obj = {}, obj1 = {}, elem;

for (i = 0, len = myData.length; i < len; i += 1) {
    elem = myData[i];
    if (!(obj1 = obj[elem.ccode])) {
        obj1 = obj[elem.ccode] = {
            ccode: elem.ccode,
            cname: elem.cname
        };
        res.push(obj1);
    }
    obj1[myData[i].year] = elem.figure;
}

console.log(res);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我会按照以下Array.prototype.reduce()的一次通过来完成这项工作;

var myData = [
 {"ccode":"AFG", "cname":"Afghanistan", "figure":"1", "year":"2012"},
 {"ccode":"AFG", "cname":"Afghanistan", "figure":"3", "year":"2013"},
 {"ccode":"AFG", "cname":"Afghanistan", "figure":"5", "year":"2014"},
 {"ccode":"AFG", "cname":"Afghanistan", "figure":"6", "year":"2015"},
 {"ccode":"AUS", "cname":"Australia", "figure":"6", "year":"2012"},
 {"ccode":"AUS", "cname":"Australia", "figure":"5", "year":"2013"},
 {"ccode":"AUS", "cname":"Australia", "figure":"7", "year":"2014"}
],
   newData = myData.reduce((p,c) => { var last = p[p.length-1];
                                      return last && last.ccode == c.ccode ? (last[c.year] = c.figure,p)
                                                                           : p.concat({   ccode : c.ccode,
                                                                                          cname : c.cname,
                                                                                       [c.year] : c.figure});
                                    },[]);
console.log(newData);