如何检查值已经存在于现有的JSON文件Node JS

时间:2018-01-12 05:39:24

标签: javascript json node.js

我有一个json文件,后端有地址..从客户端我通过API获取用户地址作为post方法。 我想检查用户输入的地址是否已存在于JSON文件中。在json文件中,地址已经是小写的格式。 我非常擅长Node和JS。这是我试过的。我收到错误"消息":" address.equals不是函数"

const addressesAsJson = require('../data/addresslist.json')

 function addressCheck (
  address /* : string | void */
) /* :Promise<Object[]> */ {

  var convertAdLowerCase = address.toLowerCase()

  return Promise.resolve()
    .then(() => {
      console.log(address)
      return addressesAsJson.filter((address) => address.equals(convertAdLowerCase))

      console.log(address.equals(convertAdLowerCase))
    })


}

我的JSON格式如下所示

{"address":"new south park , western sydney , australia 2345","display":"New South Park , WESTERN SYDNEY , AUSTRALIA 2345"}

2 个答案:

答案 0 :(得分:1)

使用相等的运算符

address === convertAdLowerCase

并删除返回后的控制台日志,因为它是无法访问的代码。

完美的代码将是

 return Promise.resolve()
    .then(() => {
      console.log(address);
      const allMatches = addressesAsJson.filter((record) => record.address === convertAdLowerCase));
      console.log(allMatches);
      return allMatches.length > 0;
 });

答案 1 :(得分:0)

Plz参考link

var a = {"address":"new south park , western sydney , australia 2345","display":"New South Park , WESTERN SYDNEY , AUSTRALIA 2345"};
var b = {"address":"New south Park , western sydney , australia 2345","display":"New South Park , WESTERN SYDNEY , AUSTRALIA 2345"}
function jsonEqual(a,b) {
    return JSON.stringify(a).toLowerCase() === JSON.stringify(b).toLowerCase();
}
console.log(jsonEqual(a, b))