2

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
1
  • You'll have to look through each object in the array and test to see if it has a property with the name you're looking for. Commented Aug 29, 2016 at 12:38

4 Answers 4

7

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

Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

1

take a look at following example code as a general answer for finding an element in an array in Javasript:

var power = [
    "Superman",
    "Wonder Woman",
    "Batman"
];

for (var i = 0; i < power.length && power[i] !== "Wonder Woman"; i++) {
    // No internal logic is necessary.
}

var rank = i + 1;

// Outputs: "Wonder Woman's rank is 2"
console.log("Wonder Woman's rank is " + rank);

I hope it can help you.

Comments

0

use like this

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

2 Comments

What if o.plugin exists, but it is undefined? Or false?
Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.