0

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);
}
3
  • Your input structure's syntax is invalid. What's the desired output? Commented Mar 23, 2021 at 18:53
  • Desired Output is. if it matches the value property, then output the value from locales array Commented Mar 23, 2021 at 18:53
  • @CertainPerformance I have updated the question with the output needed. Commented Mar 23, 2021 at 18:56

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for the answer in quick time! You saved my day :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.