2

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 6

3

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

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

Comments

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

Comments

1

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

Comments

1

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

Comments

1

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

Comments

1

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)

Comments

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.