asz999
asz999

Reputation: 23

Print object with the same value from array of objects

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

Upvotes: 1

Views: 738

Answers (3)

Harshit Agarwal
Harshit Agarwal

Reputation: 2420

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.

Upvotes: 0

Shubham Verma
Shubham Verma

Reputation: 5054

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 :

Upvotes: 0

Pablo Recalde
Pablo Recalde

Reputation: 3571

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.

Upvotes: 3

Related Questions