console.log(json2 [key2] .id)undefined

时间:2018-01-29 08:42:50

标签: json node.js undefined

我有这个node.js代码:

var json2 = JSON.parse(body2);
console.log(json2)

var arrFound2 = Object.keys(json2).filter(function(key2) {
    console.log(json2[key2].id)
    return json2[key2].id;
}).reduce(function(obj2, key2){
    obj2 = json2[key2].attempts[0].duration;
       console.log(obj2)
       return obj2;
}, {});
//console.log(arrFound);
callback(null, arrFound2);
});

当我运行它时,console.log(json2)返回json,但console.log(json2[key2].id)返回undefined。我在这里做错了什么?

这是我的JSON:

{ id: 'local-1517179209543',
  name: 'TeraGen (5MB) 30146960-047c-11e8-afb5-17a9edeb2d55',
  attempts: 
       [ { startTime: '2018-01-28T22:40:07.941GMT',
       endTime: '2018-01-28T22:40:17.739GMT',
       lastUpdated: '2018-01-28T22:40:17.000GMT',
       duration: 9798,
       sparkUser: 'paulcarron',
       completed: true,
       endTimeEpoch: 1517179217739,
       startTimeEpoch: 1517179207941,
       lastUpdatedEpoch: 1517179217000 } ] }

2 个答案:

答案 0 :(得分:1)

console.log(json2[key2].id)错误,因为过滤器函数将数组传递给回调函数。您在Object.keys(json2)上链接过滤器函数,这意味着过滤器函数将获取json2对象的键。 要获取JSON的值,您只需使用json2[key2]

https://docs.microsoft.com/en-us/scripting/javascript/reference/filter-method-array-javascript

答案 1 :(得分:1)

以下是您需要做的事情:

您只需要return json2[key2];

,而不是传递var json2 = { id: 'local-1517179209543', name: 'TeraGen (5MB) 30146960-047c-11e8-afb5-17a9edeb2d55', attempts: [ { startTime: '2018-01-28T22:40:07.941GMT', endTime: '2018-01-28T22:40:17.739GMT', lastUpdated: '2018-01-28T22:40:17.000GMT', duration: 9798, sparkUser: 'paulcarron', completed: true, endTimeEpoch: 1517179217739, startTimeEpoch: 1517179207941, lastUpdatedEpoch: 1517179217000 } ] }; console.log(json2); var arrFound2 = Object.keys(json2).filter(function(key2) { console.log(key2 , ' -----> ', json2[key2]); return json2[key2]; }).reduce(function(obj2, key2){ obj2 = json2[key2].attempts[0].duration; console.log(obj2) return obj2; }, {}); //console.log(arrFound); callback(null, arrFound2);

运行代码段,您就会明白



superagent.get(URL).then((res) => {
  for(let i in res.body) {
    if (i==='has_rejected_advisories') {
      console.log(i + "="+res.body[i]);
    }
  }
})
.catch((err) => err.message));