Avinash Singh
Avinash Singh

Reputation: 13

Filter object-array based on object name

I am trying to use array.filter() to filter an object array on the object names.

I've tried using array.constructor.name unsuccessfully.

var temp = ({ 
en: {
    id: `${scope}.en`,
    defaultMessage: 'English',
  },
  es: {
    id: `${scope}.es`,
    defaultMessage: 'Spanish',
  },
  ar: {
    id: `${scope}.ar`,
    defaultMessage: 'Arabic',
  },
});

var selectedObj = temp.filter(msg => msg.constructor.name === 'en');

Upvotes: 1

Views: 54

Answers (1)

Joel MacKenzie
Joel MacKenzie

Reputation: 32

The array.filter function only works on arrays. The Temp variable is not an array, it's an object. An array would be contained inside of square brackets []

It's not really clear to me what you're trying to do, but if your goal is to simply assign the "en" object to the selectedObj variable, then I believe the following will work:

var selectedObj = temp.en;

If you've got a variable that contains the string 'en', then maybe you could try:

var code = 'en';
var selectedObj = temp[code];

Upvotes: 1

Related Questions