推送对象数组而不是其值

时间:2017-03-03 04:14:06

标签: javascript ecmascript-6

var items = [{
    "name": "James",
    "gender": "boy"
}, {
    "name": "Sam",
    "gender": "boy"
}, {
    "name": "Alice",
    "gender": "girl"
}];

我想将性别的计数添加到上面的对象数组中。比如对于男孩来说它是2,而女孩则是1.我已经完成了它返回类别的部分。

var genderList = [];
for(var i = 0; i < items.length ; i++){
      if(genderList.indexOf(items[i].gender) < 0){
        genderList.push(items[i].gender);
       }
}

我怎样才能产生这样的结果?

[{"name":"boy","count":2},{"girl","count":1}]

3 个答案:

答案 0 :(得分:1)

您可以使用array .reduce() method来计算值 - 我建议在{"boy": 2, "girl": 1}这样的结构中输出输出,而不是显示的对象数组,因为创建,更新,并阅读。

然后,您可以将其转换为您显示的格式:

var items = [
  { "name": "James", "gender": "boy"},
  { "name": "Sam", "gender": "boy"},
  { "name": "Alice", "gender": "girl"}
];

var genderCount = items.reduce(function(a, c) {
  a[c.gender] = (a[c.gender]||0) + 1;
  return a;
}, {});
console.log(JSON.stringify(genderCount));

var asArray = Object.keys(genderCount).map(v => ({ name: v, count: genderCount[v] }));
console.log(JSON.stringify(asArray));

如果你不熟悉.reduce(),它会像下面的循环一样,除非不需要在当前范围内创建额外的工作变量:

var items = [
  { "name": "James", "gender": "boy"},
  { "name": "Sam", "gender": "boy"},
  { "name": "Alice", "gender": "girl"}
];

var genderCount = {}
for (var i = 0; i < items.length; i++) {
  genderCount[items[i].gender] = (genderCount[items[i].gender]||0) + 1;
}
console.log(JSON.stringify(genderCount));

// then as above to get your array of objects output:
var asArray = Object.keys(genderCount).map(v => ({ name: v, count: genderCount[v] }));
console.log(JSON.stringify(asArray));

注意:在上面的示例中,我只使用JSON.stringify() 使其适合一行中的控制台,它不是计数的一部分/转换过程。

答案 1 :(得分:1)

var items = [
  { "name": "T", "gender": "other"},
  { "name": "James", "gender": "boy"},
  { "name": "Sam", "gender": "boy"},
  { "name": "Alice", "gender": "girl"}
];

取上一项并比较性别类型。如果它存在,我们加1,如果不存在,那么我们创建它并添加1。

var genderTypes = items.reduce(function(prev, cur) {
  prev[cur.gender] = (prev[cur.gender]||0) + 1;
  return prev;
}, {});

console.log('genderTypes', genderTypes)

接下来,我们从对象中取出键并将它们分为性别和计数

var separateNameAndCount = Object.keys(genderTypes).map(type => ({ name: type, count: genderTypes[type] }));

console.log('separateNameAndCount', separateNameAndCount)

最后我们将对象转换为json格式

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

答案 2 :(得分:0)

试试这样。使用Array.map

&#13;
&#13;
var items = [{
    "name": "James",
    "gender": "boy"
}, {
    "name": "Sam",
    "gender": "boy"
}, {
    "name": "Alice",
    "gender": "girl"
}];
var b=0,g=0;
items.map((item)=>(item.gender=="boy")?b++:g++);
var finalArray = [{"name":"boy","count":b},{"name":"girl","count":g}]
console.log(finalArray);
&#13;
&#13;
&#13;