使用NodeJS从json数组中查找项目

时间:2014-05-19 07:18:18

标签: json node.js

尝试从json数组中搜索特定项目并重新启动项目

 result = {
      FF: {
        server: 'deskes.com',
        result: 'succes'

      },
         {
        server: 'cleantarge.com',
        result: 'Failed'

      },
         {
        server: 'fance34.com',
        result: 'success'

      },{
        server: 'deskes.com',
        result: 'Failed'

      },

    }

我有以下json数据。 我想基于服务器搜索项目

我使用了代码

var arrFound = result.filter(function(item) {
    return item.server == 'deskes.com';
});

But getting TypeError: Object #<Object> has no method 'filter'

我在搜索数据后得到的json是

result = {
  FF: {
    server: 'deskes.com',
    result: 'succes'

  },

  {
    server: 'deskes.com',
    result: 'Failed'

  }

}

3 个答案:

答案 0 :(得分:1)

filter方法仅适用于数组,看起来就像是在一个对象上调用它(来自外括号)。你可以通过循环键来解决这个问题:

var arrFound = Object.keys(result).filter(function(key) {
    return result[key].server == 'deskes.com';
// to cast back from an array of keys to the object, with just the passing ones
}).reduce(function(obj, key){
    obj[key] = result[key];
    return obj;
}, {});;

答案 1 :(得分:0)

我认为问题在于你的json,它需要是一个数组。

这是我测试过的代码示例,它运行正常。

var result = [
  {
   server: 'deskes.com',
    result: 'succes'

  },
     {
    server: 'cleantarge.com',
    result: 'Failed'

  },
     {
    server: 'fance34.com',
    result: 'success'

  },{
    server: 'deskes.com',
    result: 'Failed'

  }
];

var arrFound = result.filter(function(item) {
  return item.server == 'deskes.com';
});

console.log(arrFound);

// Outputs: [ { server: 'deskes.com', result: 'succes' }, { server: 'deskes.com', result: 'Failed' } ]

答案 2 :(得分:0)

您还可以使用ECMAScript 2015的箭头功能版本:

rta =  result.filter(
   (it) => {
     return it.server === 'deskes.com';
   }
);    

代码:

var result = [
  {
   server: 'deskes.com',
    result: 'succes'

  },
     {
    server: 'cleantarge.com',
    result: 'Failed'

  },
     {
    server: 'fance34.com',
    result: 'success'

  },{
    server: 'deskes.com',
    result: 'Failed'

  }
];



var rta =  result.filter(
   (it) => {
     return it.server === 'deskes.com';
   }
);

console.log(rta);

/*
Result:

[
  {
    "server": "deskes.com",
    "result": "succes"
  },
  {
    "server": "deskes.com",
    "result": "Failed"
  }
]

*/