Home > Net >  How to select nested object's property with map() in Javascript?
How to select nested object's property with map() in Javascript?

Time:04-01

This is my object.

values : {
  title : 'this is title ..',
  translate : {
    en : 'some texts .. ',
  },
}

And this is array I have.

arr = ['translate.en', 'title'];

What I want to do is this, but this is not work as I expected.

const value = arr.map(item => values[item]);
// (Result) value : undefined, 'this is title ..'
// (Expected) value : 'some texts .. ', 'this is title ..'

const value = arr.map(item => values.item); // error : 'item'  is declared but its value is never read.

How to get values.translate.en value using map()?

CodePudding user response:

you can use this snippet. Not the cleanest, but you get the idea

arr.map(item => {
  let arrItem = item.split('.');
  let data = values;
  for (i in arrItem) {
    data = data[arrItem[i]];
  }
  return data;
});

CodePudding user response:

Your current code is doing the following:

const values = {
    title: 'this is title ..',
    translate: {
        en: 'some texts .. ',
    },
    'translate.en': 'hello',
};

const arr = ['translate.en', 'title'];

const value = arr.map((item) => values[item]);
// (Result) value : 'hello', 'this is title ..'

If you want to do what you want to do, you should do the following:

const values = {
    title: 'this is title...',
    translate: {
        en: 'some texts... ',
    },
};

const arr = ['translate.en', 'title'];

const value = arr.map((item) => {
    let index = item.split('.');
    let value = values;
    for (i in index) {
        value = value[index[i]];
    }
    return value;
});
// (Result) value : 'come texts...', 'this is title ..'

However, if possible, I would suggest structuring your values object in the following way:

const values = {
    title: {
        kr: '타이틀',
        en: 'title'
    },
    body: {
        en: 'some texts .. ',
        kr: '어쩌고 저쩌고 .. ',
    },
};

So as long as you know which part: body or title is required and you know the language you want to get, it will be easy to get it.

  • Related