Reddy Reddy - 1 year ago 104
Javascript Question

Find if an element exists in Javascript array

I am trying to find if an element exists in

with a name.
Couldn't figure out, how to achieve the same

let string = [{"plugin":[""]}, {"test": "123"}]
console.log(string instanceof Array); //true
console.log("plugin" in string); //false

Answer Source

plugin is not defined directly in the array, it is defined inside the object in the array.

Use the Array#find to check if any element in the array contain the given property.

array.find(o => o.hasOwnProperty('plugin'))

Use hasOwnProperty to check if object is having property.

let array = [{"plugin":[""]}, {"test": "123"}];
let res = array.find(o => o.hasOwnProperty('plugin'));


As an option, you can also use Array#filter.

array.filter(o => o.hasOwnProperty('plugin')).length > 0;

let array = [{"plugin":[""]}, {"test": "123"}];
let containsPlugin = array.filter(o => o.hasOwnProperty('plugin')).length > 0;


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download