将JS数组转换为对象

时间:2016-11-02 07:31:54

标签: javascript arrays json sorting

我有一个问题,正确的转换数组到我需要从图形插件的形式。我有一个JSON,如下所示,从这个文件我需要计算我有多少头衔(见图1)。希望你能从图片中理解。

[
  {
    "name": "Mike Frost",
    "title": "value_1",
    "gender": "Male"
  },
  {
    "name": "Hans Karl",
    "title": "value_6",
    "gender": "Male"
  },
  {
    "name": "Kelly Clarkson",
    "title": "value_3",
    "gender": "Female"
  },
  ...
]

这是我迄今为止所做的:

enter image description here

这就是我需要的:

enter image description here

我的脚本会根据JSON计算值。

var employeeData = require('json!../path/to/json.json');
var obj = [];
for (var i = 0, j = employeeData.length; i < j; i++) {
    if (obj[employeeData[i]['title']]) {
        obj[employeeData[i]['title']]++;
    }
    else {
        obj[employeeData[i]['title']] = 1;
    }
}

3 个答案:

答案 0 :(得分:1)

一种方便的方法是使用地图(如果您正在使用ES2015,则为真实Map;如果您使用的是ES5或更早版本,则为我们用作地图的对象)。您构建一个新数组,并跟踪由value_X值键入的地图中的数组条目:

var json = '[' +
'  {' +
'    "name": "Mike Frost",' +
'    "title": "value_1",' +
'    "gender": "Male"' +
'  },' +
'  {' +
'    "name": "Hans Karl",' +
'    "title": "value_6",' +
'    "gender": "Male"' +
'  },' +
'  {' +
'    "name": "Another Six",' +
'    "title": "value_6",' +
'    "gender": "Male"' +
'  },' +
'  {' +
'    "name": "Kelly Clarkson",' +
'    "title": "value_3",' +
'    "gender": "Female"' +
'  },' +
'  {' +
'    "name": "Another 3",' +
'    "title": "value_3",' +
'    "gender": "Female"' +
'  },' +
'  {' +
'    "name": "Yet Another 3",' +
'    "title": "value_3",' +
'    "gender": "Female"' +
'  }' +
']';

// Parse the JSON
var data = JSON.parse(json);

// The new array we'll build
var newArray = [];

// Our "map"
var map = Object.create(null);

// Loop the parsed data
data.forEach(function(entry) {
    // Get the existing new entry if any
    var mapEntry = map[entry.title];
    if (mapEntry) {
        // We have one, increase its `value`
        ++mapEntry.value;
    } else {
        // There isn't one, create it with a count of 1
        // and save it to the array
        mapEntry = map[entry.title] = {
            label: entry.title,
            value: 1
        };
        newArray.push(mapEntry);
    }
});

// Done
console.log(newArray);

这可以写得更简洁,但我想说出我正在做的事情的各个部分。

在ES2015 +中:

const json = `[
  {
    "name": "Mike Frost",
    "title": "value_1",
    "gender": "Male"
  },
  {
    "name": "Hans Karl",
    "title": "value_6",
    "gender": "Male"
  },
  {
    "name": "Another Six",
    "title": "value_6",
    "gender": "Male"
  },
  {
    "name": "Kelly Clarkson",
    "title": "value_3",
    "gender": "Female"
  },
  {
    "name": "Another 3",
    "title": "value_3",
    "gender": "Female"
  },
  {
    "name": "Yet Another 3",
    "title": "value_3",
    "gender": "Female"
  }
]`;

// Parse the JSON
const data = JSON.parse(json);

// The new array we'll build
const newArray = [];

// Our map
const map = new Map();

// Loop the parsed data
data.forEach(entry => {
    // Get the existing new entry if any
    let mapEntry = map.get(entry.title);
    if (mapEntry) {
        // We have one, increase its `value`
        ++mapEntry.value;
    } else {
        // There isn't one, create it with a count of 1
        // and save it to the array
        mapEntry = {
            label: entry.title,
            value: 1
        };
        map.set(entry.title, mapEntry);
        newArray.push(mapEntry);
    }
});

// Done
console.log(newArray);

答案 1 :(得分:0)

您可以迭代数组并计算相同标题的出现次数。

&#13;
&#13;
var data = [{ "name": "Mike Frost", "title": "value_1", "gender": "Male" }, { "name": "Hans Karl", "title": "value_6", "gender": "Male" }, { "name": "Kelly Clarkson", "title": "value_3", "gender": "Female" }, { "name": "Kelly Clarkson", "title": "value_3", "gender": "Female" }, ],
    result = data.reduce(function (hash) {
        return function (r, a) {
            if (!hash[a.title]) {
                hash[a.title] = { label: a.title, value: 0 };
                r.push(hash[a.title]);
            }
            hash[a.title].value++;
            return r;
        };
    }(Object.create(null)), []);

console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

ES6 with Map

&#13;
&#13;
var data = [{ "name": "Mike Frost", "title": "value_1", "gender": "Male" }, { "name": "Hans Karl", "title": "value_6", "gender": "Male" }, { "name": "Kelly Clarkson", "title": "value_3", "gender": "Female" }, { "name": "Kelly Clarkson", "title": "value_3", "gender": "Female" }, ],
    result = data.reduce(
        (map =>
            (r, a) =>
                (!map.has(a.title) && map.set(a.title, r[r.push({ label: a.title, value: 0 }) - 1]), map.get(a.title).value++, r)
        )(new Map), []);

console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用Array.prototype.reduce和哈希表对数据进行分组 - 请参阅下面的演示:

&#13;
&#13;
var object=[{name:"Mike Frost",title:"value_1",gender:"Male"},{name:"Hans Karl",title:"value_6",gender:"Male"},{name:"Kelly Clarkson",title:"value_3",gender:"Female"},{name:"Mike Frost",title:"value_1",gender:"Male"},{name:"Hans Karl",title:"value_6",gender:"Male"}];

var result = object.reduce(function(hash){
   return function(prev, curr){
     if(hash[curr.title])
       hash[curr.title].value++;
     else {
       hash[curr.title] = {label: curr.title, value: 1};
       prev.push(hash[curr.title]);
     }
     return prev;
   };
}(Object.create(null)), []);

console.log(result);
&#13;
.as-console-wrapper{top:0;max-height:100%!important;}
&#13;
&#13;
&#13;