首页 > 解决方案 > 如何在javascript中验证对象

问题描述

我想知道如何使用javascript中的输入对象验证对象是否存在

我有结果对象,应该检查其他输入对象中是否存在该属性,如果全部存在则返回 true 否则为 false

/* result object */
var result_query= {
  send_country: 'Singapore', // check if exist in obj_cn 'country_name'
  sccy: 'SGD', // check if exist in obj_cn 'country-from'
  receive_country: 'India', // check if exist in obj_cn'popular_to'
  rccy: 'INR' // check if exist in obj_ccy 'currency' by using receive_country 
}
/*if all exists return true , if single value doesnot exist return false*/


/* others object */
var paramValue = ["Singapore", "India"];
var obj_cn = [
{
  country_name: "Singapore",
  country_from:["SGD"],
  popular_to: ["India"],
  country_to: ["SGD"],
  country_code: "SG"
},
{
  country_name: "India",
  country_from:["INR"],
  popular_to: ["UnitedStates"],
  country_to: ["USD"],
  country_code: "IN"
}
]
var obj_ccy = [
{
   currency: "SGD",
   country_code: "SG",
   country_name: "Singapore"
}
]

标签: javascriptjqueryarraysobject

解决方案


您可以使用filter()包含对象的 javscript 数组上的函数以及indexOf()仅包含字符串的数组来执行此操作。

将代码写在一个片段中,但我建议用它制作一个函数。

//Source data objects
var obj_cn = [{
  country_name: "Singapore",
  country_from:["SGD"],
  popular_to: ["India"],
  country_to: ["SGD"],
  country_code: "SG"
}];

var obj_ccy = [{
   currency: "SGD",
   country_code: "SG",
   country_name: "Singapore"
}];

var result_query = {
  send_country: 'Singapore', // check if exist in obj_cn 'country_name'
  sccy: 'INR', // check if exist in obj_cn 'country-from'
  receive_country: 'India', // check if exist in obj_cn'popular_to'
  rccy: 'INR' // check if exist in obj_ccy 'currency' by using receive_country 
};

//city check
var cityFound = obj_cn.filter(function(cn) {
  return cn.country_name == result_query.send_country;
}).length > 0;

//sccy check
var sccyFound = obj_cn.filter(function(cn) {
  return cn.country_from.indexOf(result_query.sccy) != -1;
}).length > 0;

//country check
var countryFound = obj_cn.filter(function(cn) {
  return cn.popular_to.indexOf(result_query.receive_country) != -1;
}).length > 0;

//ccy check
var ccyFound = obj_cn.filter(function(ccy) {
  return ccy.currency == result_query.rccy;
}).length > 0;

//test results
console.log("City found: " + cityFound);
console.log("Sccy found: " + sccyFound);
console.log("Country found: " + countryFound);
console.log("Ccy found: " + ccyFound);
console.log("All found: " + (cityFound && sccyFound && countryFound && ccyFound));


推荐阅读