scriobh
scriobh

Reputation: 890

Get only specific values in array of objects in JavaScript

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

Upvotes: 3

Views: 8252

Answers (5)

Elciney Júnior
Elciney Júnior

Reputation: 76

I think that you want to do this -

arr.filter((obj) => obj.label == "one" || obj.label == "two");

Upvotes: 1

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5786

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

You don't have to use map. You can directly filter you array using filter() which takes a function(that will be take each element of the array as parameter) and returns a new array with only the elements that matches the specified condition of the function.

You can do it as follows -

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


let filtered_arr = arr.filter((obj)=> obj.label==='one' || obj.label==='two');

console.log(filtered_arr)

Upvotes: 0

iAmOren
iAmOren

Reputation: 2804

Use the filter method:

arr.filter(obj => ((obj.label=="one")||(obj.label=="two")))

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89374

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)

Upvotes: 3

Pac0
Pac0

Reputation: 23174

You want to change your condition as a 'OR' (|| instead of &&), because one particular element cannot have label that is, at the same time, both 'one' and 'two'.

You want that a particular element has label that is either 'one' or 'two'

Upvotes: 1

Related Questions