透视或转换JavaScript对象

时间:2017-06-09 03:34:29

标签: javascript json

我有以下JavaScript对象。我需要从给定的对象生成一个新对象。我应该在JavaScript中采用什么方法?

[
 {"name": "Dan",  "city" : "Columbus", "ZIP":"47201"},
 {"name": "Jen",  "city" : "Columbus", "ZIP":"47201"},
 {"name": "Mark", "city" : "Tampa",  "ZIP":"33602"},
]

如何转换或透视以生成以下对象?

[
 { "47201": [
              {"name": "Dan", "city": "Columbus"},
              {"name": "Jen", "city": "Columbus"},
             ],
    "count": "2"
  },
  { "33602": [
              {"name": "Mark", "city": "Tampa"}
             ],
    "count": "1"
  }
 ]

2 个答案:

答案 0 :(得分:1)

我不知道为什么你想要.count属性,当可以通过数组的.length属性访问它时,无论如何:

const input = [
  {"name": "Dan",  "city" : "Columbus", "ZIP":"47201"},
  {"name": "Jen",  "city" : "Columbus", "ZIP":"47201"},
  {"name": "Mark", "city" : "Tampa",  "ZIP":"33602"},
]

const working = input.reduce((acc, {ZIP, name, city}) => {
  (acc[ZIP] || (acc[ZIP] = [])).push({name, city})
  return acc
}, {})

const output = Object.keys(working)
  .map(k => ({[k]: working[k], count: working[k].length}))

console.log(output)

进一步阅读:

答案 1 :(得分:0)

以下代码适用于您的要求。最终结果存储在保存数组对象的变量result中。

    var source = [{
            "name": "Dan",
            "city": "Columbus",
            "ZIP": "47201"
        },
        {
            "name": "Mark",
            "city": "Tampa",
            "ZIP": "33602"
        },
        {
            "name": "Jen",
            "city": "Columbus",
            "ZIP": "47201"
        }
    ];

    var result = [];
    finalarr('ZIP');

    function finalarr(propname) {
        var obj = JSON.parse(JSON.stringify(source));

        obj.forEach(function(elm,i) {
            var arr = {};var chli=[];var charr={};
            var flag = 0;

            for (var prop in elm) {
                if(prop != propname){
                    charr[prop]=elm[prop];
                }
            }

            for(var i=0;i<result.length;i++){
                if(result[i][elm[propname]]){
                    result[0][elm[propname]].push(charr);
                    //console.log(result[i][propname]);
                    flag = 1;
                }
            }

            if(flag == 0){
                chli.push(charr);
                arr["count"] = checkarr(obj,propname,elm[propname]);        
                arr[elm[propname]]=chli;
                result.push(arr);
            }
        });
    }

    function checkarr(obj,propname,value){
        var count = 0;
        obj.forEach(function(elm,i) {
            if(elm[propname] == value){
                count++;
            }
        });

        return count;
    }

console.log(result);