javascript - 如何在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"
}
]
解决方案
您可以使用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));
推荐阅读
- tensorflow - 使用photoshop完成tensorflow对象检测中的欠采样?
- firefox - Mozilla 选择选项勾号图标丑陋
- regex - 拆分正则表达式与行尾或字符匹配
- php - 从PHP中的数组中删除具有多个共同值的元素
- node.js - 我什么时候应该使用工作线程?
- active-directory - LDAP searchResEntry - 值的顺序
- java - 如何使用拆分数组?
- spring - Spring Cloud Stream 中 Kafka 标头上的条件(基于内容)路由
- python - 检查是否列出类型别名的类型
- android - 查找可能添加到 firebase 的数据