Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check and get data from an array in JavaScript

Tags:

javascript

I have an object:

var Obj1 = {id: 1, name: 'Apple'}

And an array object:

var ArrObj = [ {id: 1, name: 'Apple', 'eat': 'rice}, {'id: 2', 'name': 'Banana'}]

How do I check Obj1.id in ArrObj? And I want the result to be: { id:1, name: 'Apple', 'eat':'rice'}

like image 578
hieu pham ba Avatar asked Jul 24 '18 08:07

hieu pham ba


People also ask

How do you check an array contains a value in JavaScript?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

How do you check if a value is in an array?

isArray(variableName) method to check if a variable is an array. The Array. isArray(variableName) returns true if the variableName is an array. Otherwise, it returns false .

How do I get an element from an array?

get() is an inbuilt method in Java and is used to return the element at a given index from the specified Array. Parameters : This method accepts two mandatory parameters: array: The object array whose index is to be returned.

How do you check if it's an array in JavaScript?

The isArray() method returns true if an object is an array, otherwise false .


2 Answers

You can use Array.find():

var Obj1 = {id: 2, name: 'Banana'}
var ArrObj = [ {id: 1, name: 'Apple', 'eat': 'rice'}, {'id': 2, 'name': 'Banana'}];
var res = ArrObj.find(({id}) => id === Obj1.id );
console.log(res);

You can also use array destructuring way like:

var Obj1 = {id: 2, name: 'Banana'}
var ArrObj = [ {id: 1, name: 'Apple', 'eat': 'rice'}, {'id': 2, 'name': 'Banana'}];
var res = ArrObj.find(({id}) => id === Obj1.id);
console.log(res);
like image 61
Ankit Agarwal Avatar answered Oct 17 '22 08:10

Ankit Agarwal


You could also use the filter function like this:

let result = ArrObj.filter(obj => {
  return obj.id == Obj1.id
})

Documentation is here: Array.prototype.filter()

like image 37
SylvainF Avatar answered Oct 17 '22 09:10

SylvainF