'How to select nested object's property with map() in Javascript?
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()?
Solution 1:[1]
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;
});
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | arbghl |
| Solution 2 | cSharp |
