Javascript Check If Values Exist in Array Json

Check whether a value exists in JSON object

var JSON = [{"name":"cat"}, {"name":"dog"}];

The JSON variable refers to an array of object with one property called "name".
I don't know of the best way but this is what I do?

var hasMatch =false;

for (var index = 0; index < JSON.length; ++index) {

var animal = JSON[index];

if(animal.Name == "dog"){
hasMatch = true;
break;
}
}

How to check if value exist in a json array javascript

No need to know the length, you can use forEach

posts.forEach(post => {
if(post.name.includes("politics")){
//Doing Stuff
}
});

How to check if a value(substring) exists in every JSON object in an array

Here is a solution that requires every object in the array to have at least some (i.e., at least one) of it's values to be a string and include the string "test".

var el = [
{ id: 28, Title: "US", Name: "testA" },
{ id: 56, Title: "US", Name: "testB" },
{ id: 89, Title: "testDefault", Name: "Joe" },
];

const exists = el.every(obj => {
return Object.values(obj).some(item => {
return typeof item === "string" && item.includes("test");
});
});

console.log(exists);

How to check if value already exists in javascript JSON array?

ComfyJS.onChat = (user, message, flags, self, extra) => {
const exists = scoreBoard.find(fn => fn.name === user)
if (exists) return;
scoreBoard.push({
name: user,
score: message
});

var data = JSON.stringify(scoreBoard);

fs.writeFile('database.json', data, function(err) {
if (err) {
console.log('There has been an error saving your configuration data.');
console.log(err.message);
return;
}
console.log('Configuration saved successfully.')
});
}

How to check if the JSON Object array contains the value defined or not?

You can combine basic array/object functions to archive your goal.
But as i commented on your question, you should define strict filter criterias.

const data = {
"ip": "103.26.208.254",
"version": "IPv4",
"city": "Jakarta",
"region": "Jakarta",
"region_code": "JK",
"country": "ID",
"country_name": "Indonesia",
"country_code": "ID",
"country_code_iso3": "IDN",
"country_capital": "Jakarta",
"country_tld": ".id",
"continent_code": "AS",
"in_eu": false,
"postal": null,
"latitude": -6.1741,
"longitude": 106.8296,
"timezone": "Asia/Jakarta",
"utc_offset": "+0700",
"country_calling_code": "+62",
"currency": "IDR",
"currency_name": "Rupiah",
"languages": "id,en,nl,jv",
"country_area": 1919440.0,
"country_population": 267663435.0,
"asn": "AS18103",
"org": "Neuviz Net"
};

// create a regex of each filter value
const filters = [
"republik",
"telekomunikasi",
"fastnet", "indosatm2",
"telekomunikasi", "indosat",
"cyberindo", "biznet", "xl",
"telematika", "hutchison",
"smartfren", "mnc",
"wireless indonesia",
"antar nusa", "biznet",
"ezecom", "win", "axis",
"linknet-fastnet", "indonesia",
"bali", "linknet", "indosat",
"antar nusa", "indo", "firstmedia",
"s.i", "cambodia", "neuviz"
].map((v) => {
return new RegExp(`${v}`, "gi");
});


// get array of values from object
// filter array based on the test criteria
let matches = Object.values(data).filter((v) => {

// conver every value to astring
let value = String(v).toLowerCase();

// test each filter on value
return filters.some((filter) => {

// test the regular expression on the value
return filter.test(value);

});

});


if (matches.length > 0) {

console.log("Filter matched!", matches);

} else {

console.log("Filte *not* matched")

}

How can I check if array contains value in Javascript for JSON data?

In the data structure of data.json file, the parent_id may be an integer or may be an array of integers.

Example of parent_id as an integer:

 {
"id": 8,
"name": "LG support",
"parent_id": 5
}

Example of parent_id as an array:

{
"id": 7,
"name": "UPS",
"parent_id": [3, 4]
}

In your code, however, you are not considering the second case (parent_id as an array).

So, in the if statement where you make this comparison, you have to add an or to handle cases where the row has parent_id as an array.

Instead of

if(value.parent_id == parent_id) {
html_code += '<option value="'+value.id+'">'+value.name+'</option>';
}

You should use the code bellow that handles arrays as well (using the Array.isArray() and the Array.include() functions):

if(value.parent_id == parent_id || 
(Array.isArray(value.parent_id) && value.parent_id.includes(+parent_id)))
{
html_code += '<option value="'+value.id+'">'+value.name+'</option>';
}

Here is a complete working snippet (selecting service delivery in the first <select> will eventually present the UPS option in the third <select>):

(Warning: in the snippet to make it work I have overriden the $.getJSON, DO NOT copy that part of the code).

$(document).ready(function(){

load_json_data('service');

function load_json_data(id, parent_id)
{
console.log('id = ' + id + ', parent_id = ' + parent_id);
var html_code = '';
$.getJSON('data.json', function(data)
{
html_code += '<option value="">Select '+id+'</option>';

$.each(data, function(key, value)
{
//console.log(key + ' - ' + JSON.stringify(value));
if(id == 'service')
{
if(value.parent_id == '0')
{
html_code += '<option value="'+value.id+'">'+value.name+'</option>';
}
}
else
{
if(value.parent_id == parent_id || (Array.isArray(value.parent_id) && value.parent_id.includes(+parent_id)))
{
html_code += '<option value="'+value.id+'">'+value.name+'</option>';
}
}
});
$('#'+id).html(html_code);
});

}

$(document).on('change', '#service', function(){
var service_id = $(this).val();
if(service_id != '')
{
load_json_data('item', service_id);
$('#contact').html('<option value="">Select contact</option>');
}
else
{
$('#item').html('<option value="">Select item</option>');
$('#contact').html('<option value="">Select contact</option>');
}
});
$(document).on('change', '#item', function(){
var item_id = $(this).val();
if(item_id != '')
{
load_json_data('contact', item_id);
}
else
{
$('#contact').html('<option value="">Select contact</option>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script type="text/javascript">
$.getJSON = function(file, callback){
var data = [
{
"id": 1,
"name": "Delivery",
"parent_id": 0
},
{
"id": 2,
"name": "Repair",
"parent_id": 0
},
{
"id": 3,
"name": "Quick Deliver",
"parent_id": 1
},
{
"id": 4,
"name": "Slow Deliver",
"parent_id": 1
},
{
"id": 5,
"name": "Aircon",
"parent_id": 2
},
{
"id": 6,
"name": "Television",
"parent_id": 2
},
{
"id": 7,
"name": "UPS",
"parent_id": [3, 4]
},
{
"id": 8,
"name": "LG support",
"parent_id": 5
},
{
"id": 9,
"name": "Toshiba support",
"parent_id": 6
}
];
callback(data);
};

</script>
<select id="service"></select>
<select id="item"></select>
<select id="contact"></select>


Related Topics



Leave a reply



Submit