1

Assuming my current object is this below:

{
    "name": 1
    "type": 2
    "kind": 2
}

I want to print all the objects in the array that have the same "type" as my current object, which is 2.

[
{
   "name": 1
   "type": 2
   "kind": 3
},
{
   "name": 2
   "type": 2
   "kind": 1
},
{
   "name": 2
   "type": 1
   "kind": 3
}
]

EXPECTED OUTPUT:

[
{
   "name": 1
   "type": 2
   "kind": 3
},
{
   "name": 2
   "type": 2
   "kind": 1
}
]

3 Answers 3

3

Use Array.prototype.filter() MDN

Like fullArray.filter(element => element.type == myObject.type) or if you are still using ES5 fullArray.filter(function(element) { return element.type == myObject.type; })

Beware I’m not on a computer, so I can’t test the code.

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

Comments

0

The answer is array filter :

    let array = [
{
"name": 1,
"type": 2,
"kind": 3
},
{
"name": 2,
"type": 2,
"kind": 1
},
{
"name": 2,
"type": 1,
"kind": 3
}
]
let customFilteredArray = array.filter(data => data.type===2) //you can add your custom check

Here is example :

Comments

0

To get the objects which has some particular value for a property from an array can be achieved using Array.filter() method. Use it like this:

let arr = [
"name": 1,
"type": 2,
"kind": 3
},
{
"name": 2,
"type": 2,
"kind": 1
},
{
"name": 2,
"type": 1,
"kind": 3
}
];

let filteredArr = arr.filter(item => item.type === 2);

The filteredArr will only have objects whose type is 2. Hope this helps.

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.