Javascript JSON拉不会正确迭代?

时间:2016-12-30 22:43:22

标签: javascript json

所以我有这段代码:

{{
        "TaskID": 35708,
        "TaskDate": "2011-06-20T00:00:00",
        "Technician": "UCH - Billy Metcalf"
    },
{
        "TaskID": 35708,
        "TaskDate": "2011-06-19T00:00:00",
        "Technician": "Edward F. Dawson"
    }
}

我的task.json文件如下所示:

[{Technician:'UCH - Billy Metcalf',Count:0},
{Technician:'Edward F. Dawson',Count:0}]

当我使用我的data.js文件上的节点运行我的文件时,我得到一个如下所示的返回:

{Technician:'Edward F. Dawson',Count:5}

整点是soo,而不是计数总是为零我想让它通过json文件,如果它发现我的新变量dps中已存在json文件,以增加计数并保留我的新数组dps与不重复的名称截然不同,例如,如果有5" Edward F. Dawson"

Partial

2 个答案:

答案 0 :(得分:0)

试试这个。如果你仔细阅读,代码应该是不言自明的。

var input=require('./task.json');
const _ = require(`underscore`);
var dps = [];
var found=0;
for(var element in input) {
    found=0
    for (var i=0;i>dps.length;i++){
        if(dps[i].Technician===input[element].Technician){
            console.log("name already exists");
            dps[i].count=dps[i].Count+1;
            found=1
        }

    }
    if ( found === 0){ // only if we did not find !
        dps.push({Technician: input[element].Technician, Count:1});
    }
}

  console.log(dps);

答案 1 :(得分:0)

您的task.json文件中包含无效的JSON。要表示对象数组,请使用括号 []包围对象,而不是花括号{}。

将JSON转换为数组后,您将能够运行以下代码:

var input = require('./task.json');
const _ = require(`underscore`);
var dps = [];
input.forEach(function (element) {
    var found = dps.some(function (elem) {
      if (elem.Technician === element.Technician) {
          elem.Count = elem.Count + 1;
          return true;
      }
    });
    if (!found) {
      dps.push({Technician: element.Technician, Count: 1});
    }
});

console.log(dps);

除此之外,如果使用.reduce()

更符合您的口味,您可以采用更实用的方法
var dps = input.reduce(function (arr, currElem) {
    var found = arr.some(function (elem) {
      if (elem.Technician === currElem.Technician) {
          elem.Count = elem.Count + 1;
          return true;
      }
    });
    if (!found) {
      arr.push({Technician: currElem.Technician, Count: 1});
    }
    return arr;
}, []);

console.log(dps);

以下是行动中的代码:



var input = [{
  "TaskID": 35708,
  "TaskDate": "2011-06-20T00:00:00",
  "Technician": "UCH - Billy Metcalf"
}, {
  "TaskID": 35708,
  "TaskDate": "2011-06-19T00:00:00",
  "Technician": "Edward F. Dawson"
}, {
  "TaskID": 35708,
  "TaskDate": "2011-06-19T00:00:00",
  "Technician": "Edward F. Dawson"
}, {
  "TaskID": 35708,
  "TaskDate": "2011-06-19T00:00:00",
  "Technician": "Edward F. Dawson"
}, ];
var dps = input.reduce(function (arr, currElem) {
    var found = arr.some(function (elem) {
      if (elem.Technician === currElem.Technician) {
          elem.Count = elem.Count + 1;
          return true;
      }
    });
    if (!found) {
      arr.push({Technician: currElem.Technician, Count: 1});
    }
    return arr;
}, []);

console.log(dps);