从对象切片属性和计数

时间:2016-08-19 13:29:39

标签: javascript arrays json object

是否可以从像

这样的对象数组中切割单个属性
[{"name":"Bryan","id":016, "counter":0}, {"name":"John","id":04, "counter":2}, {"name":"Alicia","id":07, "counter":6}, {"name":"Jenny","id":015, "counter":9}, {"name":"Bryan","id":016, "counter":0}, {"name":"Jenny","id":015, "counter":9}, {"name":"John","id":04, "counter":2}, {"name":"Jenny"    ,"id":015, "counter":9}];

我试图从每个对象切片name并计算相同元素的数量(有3个名称为Jenny的对象)以实现以下结构:

[{"name":"Bryan","Number":2},
{"name":"John","Number":2},
{"name":"Alicia","Number":1},
{"name":"Jenny","Number":3}]

3 个答案:

答案 0 :(得分:2)

您是否要忽略已存在的idcounter道具?

您可以创建一个对象来跟踪唯一名称,并最终转换回数组:

var data = [{"name": "Bryan",  "id": 016,  "counter": 0}, {  "name": "John",  "id": 04,  "counter": 2}, {  "name": "Alicia",  "id": 07,  "counter": 6}, {  "name": "Jenny",  "id": 015,  "counter": 9}, {  "name": "Bryan",  "id": 016,  "counter ": 0}, {  "name": "Jenny",  "id": 015,  "counter ": 9}, {  "name": "John",  "id": 04,  "counter": 2}, {  "name": "Jenny",  "id": 015,  "counter": 9}];

var result = data.reduce(function(result, item) {
  if (!result[item.name]) {
    result[item.name] = {
      name: item.name,
      counter: 0
    };
  }

  result[item.name].counter += 1;
  
  return result;
}, {});

console.log(Object.keys(result).map(function(key) { return result[key] }));

答案 1 :(得分:1)

您可以使用哈希表作为对计数名称的引用。

var data = [{ name: "Bryan", id: "016", counter: 0 }, { name: "John", id: "04", counter: 2 }, { name: "Alicia", id: "07", counter: 6 }, { name: "Jenny", id: "015", counter: 9 }, { name: "Bryan", id: "016", counter: 0 }, { name: "Jenny", id: "015", counter: 9 }, { name: "John", id: "04", counter: 2 }, { name: "Jenny", id: "015", counter: 9 }],
    grouped = [];

data.forEach(function (a) {
    if (!this[a.name]) {
        this[a.name] = { name: a.name, Number: 0 };
        grouped.push(this[a.name]);
    }
    this[a.name].Number++;
}, Object.create(null));

console.log(grouped);

答案 2 :(得分:1)

给它一个机会。我们创建一个名称字典,其计数称为nameDict,并遍历列表以计算它们。

var arr = [{"name":"Bryan","id":"016", "counter":0}, {"name":"John","id":"04", "counter":2}, {"name":"Alicia","id":"07", "counter":6}, {"name":"Jenny","id":"015", "counter":9}, {"name":"Bryan","id":"016", "counter":0}, {"name":"Jenny","id":"015", "counter":9}, {"name":"John","id":"04", "counter":2}, {"name":"Jenny","id":"015", "counter":9}];
var nameDict = {};

for(var i = 0; i < arr.length; i++)
{
    var name = arr[i].name;
    if(nameDict[name] == undefined){
        //haven't encountered this name before so we need to create a new entry in the dict
        nameDict[name] = 1
    } else {
        //otherwise increment the count
        nameDict[name] += 1
    }
}

console.log(JSON.stringify(nameDict));