7

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'}

2

3 Answers 3

12

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

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

3 Comments

@hieuphamba glad to help. You can tick mark the answer if it was helpful.
second answer doesn't work right now (it just returns the first element with a truthy id value)
@SandroKSG it does now
3

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

Comments

0

all right! you can also add array and get it by code :

var obj = '{ "name" : "amr" , "age" : "16"}';
var obj1 = JSON.parse(obj);
alert("yourname is : "+obj1.name+" , your age is "+obj1.age);
// it get name > amr and age > 16
it's very easy :)

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.