tkamath99
tkamath99

Reputation: 649

Split characters from elements in array of object in JavaScript

I have a following array of Object, I wanted to match the Object Keys from locales array and match with the value property in the object.

Output: If the Object key from locales matches the value property, then i want to display the text in Object values from locales.

What i have in an array is:

[{
 value: 'dz'
 locales: [
    {ar-dz: "Hello World"},
    {ar-dk: "Hello World"}
 ]
}]

I am stuck in a logic beyond this point.

for(var i = 0; i < data.locales.length; i++) {
    var localearray = Object.keys(data.locales[i]));
    var locales = localearray[i].split('-');
    console.log(locales);
}

Upvotes: 0

Views: 48

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371193

Use .find on the objects to identify the first object whose (only) key's suffix after the - matches the value you're looking for:

const obj = {
 value: 'dz',
 locales: [
    {'ar-dz': "Hello World"},
    {'ar-dk': "Hello World"}
 ]
};

const locale = obj.locales.find(
  locale => obj.value === Object.keys(locale)[0].split('-')[1]
);
if (locale) console.log(Object.values(locale)[0]);

Note that you also

  • need commas between separate key-value pairs

  • need to surround invalid identifiers in object literals with ' or " delimiters

Upvotes: 1

Related Questions