How to check if exist key in array? [duplicate]

48
August 08, 2019, at 8:10 PM

This question already has an answer here:

  • In an array with objects, check if a key exists in any of those objects 5 answers

I have array arr:

var arr = [{1: []}, {2: []}, {3: []}]

How to check of 1 is present in array in object {1: []}?

Answer 1

Code below solves your problem:

const arr = [{1: []}, {2: []}, {3: []}];
const element = arr.find(x => {
    const key = Object.keys(x)[0];
    return key === "1";
});
const hasKey = !!element;

you should remember that the key is always a string. you can also replace the fourth line by

return key == 1;

I personally recommend using the strict equals check

Answer 2

You can use the ES6 find method as

let key = 1    
let arr = [{1: []}, {2: []}, {3: []}];
Object.keys(arr).find((val) => val == key)

If found, it will return the key else undefined.

READ ALSO
Calling a static method on a variable rather than class

Calling a static method on a variable rather than class

So I am writing some Scala tests for some Java code (I am very new at both of them)What I am trying to do is instead of calling

18
How can I reset the thumb on JavaFX Slider?

How can I reset the thumb on JavaFX Slider?

I'm making an image viewer on JavaFXThe zoom is controlled with a slider but if I zoom an image and then load another one, the thumb on the slider stands where I left it, but the new image loads at x1 zoom

56
How to set toolbar title appear on scroll from bottom as it implemented in Apple Music Android app?

How to set toolbar title appear on scroll from bottom as it implemented in Apple Music Android app?

I want to implement scroll behavior for Toolbar title as its implemented in Apple Music Android app

41
Day Difference Between Two Hebrew Date In Java

Day Difference Between Two Hebrew Date In Java

I have two Hebrew calendar date instance ie date1 and date2

31