Javascript 计算地图外部的项目长度

Javascript 计算地图外部的项目长度,javascript,ecmascript-6,Javascript,Ecmascript 6,我有一个类似这样的json var person = [{ "name": "john", "age": 20 }, { "name": "Samuel", "age": 10 }, { "name": "Jin", "age": 10 }] 我的欲望输出是 age 10 (2) - Samuel - Jin age 20 (1) - John 我数总数有问题。我愿意 ages.map(doList) //where ages is [10,

我有一个类似这样的json

var person = [{
    "name": "john",
    "age": 20
}, {
    "name": "Samuel",
    "age": 10
}, {
    "name": "Jin",
    "age": 10
}]
我的欲望输出是

age 10 (2)
- Samuel
- Jin

age 20 (1)
- John
我数总数有问题。我愿意

ages.map(doList) //where ages is [10,20]

doList(age) {
    persons.filter(p => p.age === age)
    .map(p => {
       p.name
    })
}

但是如何打印出年龄组的长度呢?

您可以更改数据结构,以便更方便地输出

var person = [{
    "name": "john",
    "age": 10
}, {
    "name": "Samuel",
    "age": 10
}, {
    "name": "Jin",
    "age": 10
}];



let newArray = [];
person.forEach((p) => {
  let findPreviousIndex = newArray.findIndex((itm) =>{
    return itm.age == p.age;
  });

  if(findPreviousIndex > -1){
    // previous found, push the name
    newArray[findPreviousIndex].names.push(p.name);
  }else{
    // not found. create a new object and push it
    newArray.push({
      "age" : p.age,
      "names" : [].concat(p.name)
    })
  }
});

console.log(newArray);

现在,打印分组数据和查找长度变得很容易。

这里有一种方法可以生成所需的输出,首先使用
.reduce()
设置一个
结果
对象,每个年龄的属性是该年龄的名称数组,然后映射
结果
的属性,创建一个
格式化的
字符串,给出问题中的特定格式:

var-person=[{
“姓名”:“约翰”,
“年龄”:20岁
}, {
“姓名”:“塞缪尔”,
“年龄”:10岁
}, {
“姓名”:“金”,
“年龄”:10岁
}]
风险值结果=人减少((a,c)=>{
(a[c.age]| |(a[c.age]=[])).push(c.name)
归还
}, {})
console.log(结果)
var formatted=Object.keys(结果)
.map(k=>`age${k}(${result[k].length})\n${result[k].map(n=>`-${n}')。连接('\n')}`)
.join('\n\n')
console.log(格式化)

JSFIDLE:

“我有一个json”-那不是json,而是一个对象。您是否试图基于一个单独的
年龄
数组获取输出,因为您只想获取这些年龄,而不是仅仅总结
人物
数组中发生的任何年龄?@nnnnnn这甚至不是一个对象,而是一个objects@A.Lau-嗯,是的,但是数组是对象的一种类型……。@a.Lau那么解决方案是什么呢?您不能只
.length
返回的过滤器吗?
var person = [{
    "name": "john",
    "age": 20
}, {
    "name": "Samuel",
    "age": 10
}, {
    "name": "Jin",
    "age": 10
}];

// create a map where the key is the person's age and the value is a list of names
var ageMap = person.reduce(function(result, p) {
    var key = p.age;
    var name = p.name;
    if (result[key]) {
        result[key].push(name);
    } else {
        result[key] = [name];
    }
    return result;
}, {});

// traverse the map and print the names of people grouped by age
Object.keys(ageMap).forEach(function(key) {
    var value = ageMap[key];
    console.log("age " + key + " (" + value.length + ")");
    value.forEach(function(name) {
        console.log("- " + name);
    });
    console.log("");
});