I would like to know how to validate the object exists with input object in javascript
I have resultant object and should check the property exists in other input objects, if all exists return true else 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"
}
]
You can do this with the filter()
function on javscript arrays that contain objects in combination with indexOf()
for the arrays that contain strings only.
Written the code in a snippet but i recommend to make a function out of it.
//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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.