Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if an element exists in Javascript array

I am trying to find if an element exists in Array with a name. Couldn't figure out, how to achieve the same

let string = [{"plugin":[""]}, {"test": "123"}]
console.log(string);
console.log(string instanceof Array); //true
console.log("plugin" in string); //false
like image 701
RaceBase Avatar asked Feb 28 '26 23:02

RaceBase


2 Answers

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'));

console.log(res);

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;

console.log(containsPlugin);
like image 129
Tushar Avatar answered Mar 03 '26 12:03

Tushar


You can use Array#some() and Object.keys() and return true/false if object with specific key exists in array.

let string = [{"plugin":[""]}, {"test": "123"}];

var result = string.some(o => Object.keys(o).indexOf('plugin') != -1);
console.log(result)
like image 28
Nenad Vracar Avatar answered Mar 03 '26 13:03

Nenad Vracar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!