Javascript : How to check if particular key is exist or not

Viewed 67

I am getting a response by calling API. which is like this.

[{"id":213132},{"id":241132},{"id":465413},{"id":546351},{"id":164854,"data":[{"rate" : 20}]},
{"id":564656,"data":[{"rate" : 40}]}]

How can I check that for particular id, there is a key data exist or not?

Any help would be great. Thank You.

6 Answers

You can first use Array.find() to get the object with the desired ID and then check if the property data is undefined or not

const myArray = [{"id":213132},{"id":241132},{"id":465413},{"id":546351},{"id":164854,"data":[{"rate" : 20}]}];

function hasData(id) {
  const myObject = myArray.find(x => x.id === id);
  return typeof myObject !== "undefined" && typeof myObject.data !== "undefined"; 
}

console.log(hasData(164854));
console.log(hasData(241132));

let id = 164854;
result = myArray.filter((val) => {return val.id === id && val.data;});

you can use filter

 let data = [{"id":213132},{"id":241132},{"id":465413},{"id":546351},{"id":164854,"data":[{"rate" : 20}]} ];
    function hasData(key) { return !!data.filter(x=> x.id==key)[0].data }
    console.log(hasData("213132"))
    console.log(hasData("164854"))

You can use "Array.find" to check if id exists, and then you can convert the result to boolean by using "!!"

var arr = [{"id":213132},{"id":241132},{"id":465413},{"id":546351},{"id":164854,"data":[{"rate" : 20}]}]


function doesDataExist(id) {
   return !!arr.find(d => d.id == id).data
}

console.log(doesDataExist(164854))

console.log(doesDataExist(213132))

You can simply use Array.some(), it will return a boolean value based on the condition.

let arr=  [{"id":213132},{"id":241132},{"id":465413},{"id":546351, "data":[{"id":1}]},{"id":164854}];

let id = 546351;
console.log(arr.some(obj => obj.id == id && !!obj.data));

id = 213132;
console.log(arr.some(obj => obj.id == id && !!obj.data));

you can use findIndex function to find the particular id

let id = 241132;
let index = arr.findIndex((data)=> data.id == id)
index==-1 ? console.log("not find") : console.log("find index=>"+index)
Related