Javascript代码更新包括每条记录的总计数

时间:2016-10-14 14:44:12

标签: javascript arrays

我正在尝试修改一些我需要在数组中添加计数的代码。

以下是数据和代码:

var data = {
  "people": [{
      "id": "32",
      "description": "some description",
      "archived": "",
      "new": 0,
      "names": [{
        "name": "name 1",
        "translations": null
      }, {
        "name": "name 2",
        "translations": null
      }],
    }, {
      "id": "56",
      "description": "some description",
      "archived": "",
      "new": 0,
      "names": [{
        "name": "name 3",
        "translations": null
      }, {
        "name": "name 4",
        "translations": null
      }],
    }, {
      "id": "99",
      "description": "some description",
      "archived": "",
      "new": 0,
      "names": null,
    },

  ]
};

var mainData = [data];
var namesList = [];

for (var i = 0; i < mainData[0].people.length; i++) {

  var obj = mainData[0].people[i];

  if( obj.names ) {

   var nme = obj.names.map( function(item){
    return item.name; 
   });
   namesList = namesList.concat(nme);

}

}

console.log(namesList); //This should have the list of names

我需要做的是添加一个新数组,其中包含每个名称字段的计数,例如......当前的数据输出将是:

[2,2] ...因为有2条记录,每条记录包含2个名称。

我该如何添加?

1 个答案:

答案 0 :(得分:0)

只需将PlatformTransactionManager数组的长度添加到您希望保留计数的其他数组

nme

演示

&#13;
&#13;
var namesCount = [];
//...
if (obj.names) {
   var nme = obj.names.map(function(item) {
     return item.name;
   });
   namesList = namesList.concat(nme);
   namesCount.push(nme.length);
}
//..
console.log(namesCount);
&#13;
&#13;
&#13;

如果您想将其存储在原始var data = { "people": [{ "id": "32", "description": "some description", "archived": "", "new": 0, "names": [{ "name": "name 1", "translations": null }, { "name": "name 2", "translations": null }], }, { "id": "56", "description": "some description", "archived": "", "new": 0, "names": [{ "name": "name 3", "translations": null }, { "name": "name 4", "translations": null }], }, { "id": "99", "description": "some description", "archived": "", "new": 0, "names": null, }, ] }; var namesList = []; var namesCount = []; for (var i = 0; i < data.people.length; i++) { var obj = data.people[i]; if (obj.names) { var nme = obj.names.map(function(item) { return item.name; }); namesList = namesList.concat(nme); namesCount.push(nme.length); } } console.log(namesCount);上,请将其设置为某个属性

data

此外,由于您没有过滤掉或删除data.namesCount = []; //... if (obj.names) { var nme = obj.names.map(function(item) { return item.name; }); namesList = namesList.concat(nme); data.namesCount.push(nme.length); } //.. console.log(data.namesCount); 中的任何对象,因此您只需获取该数组的长度即可获得计数

obj.names