Monday, May 20, 2024
115
rated 0 times [  120] [ 5]  / answers: 1 / hits: 5828  / 4 Years ago, tue, june 23, 2020, 12:00:00

I'm trying to get only two objects in the resultant array with label one and label two.
How do I filter values in an array of objects. Could anyone please help?




const arr = [{
value: 1,
label: one
},
{
value: 2,
label: two
},
{
value: 3,
label: three
},
];

arr.map((val, index) => val.filter(val.label => val.label === 'one' && val.label === 'two'))

console.log(arr)




I was expecting an output like this below


[{
value: "1",
label: "one"
},
{
value: "2",
label: "two"
},
]

More From » ecmascript-6

 Answers
2

You can check if the label is either "one" or (not and) "two" with just filter (you don't need map).




const arr = [{
value: 1,
label: one
},
{
value: 2,
label: two
},
{
value: 3,
label: three
},
];

const res = arr.filter(val => val.label === 'one' || val.label === 'two');

console.log(res)




If there are multiple labels you want to allow, you can use a Set to store them, and use Set#has for filtering.




const arr = [{
value: 1,
label: one
},
{
value: 2,
label: two
},
{
value: 3,
label: three
},
{
value: 4,
label: four
},
{
value: 5,
label: five
},
{
value: 6,
label: six
},
{
value: 7,
label: seven
}
];
const allowedLabels = new Set([one, two, four, seven]);
const res = arr.filter(val=>allowedLabels.has(val.label));
console.log(res)




[#3392] Saturday, June 20, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlynnb

Total Points: 402
Total Questions: 96
Total Answers: 109

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
kaitlynnb questions
;