這是我的物件。
values : {
title : 'this is title ..',
translate : {
en : 'some texts .. ',
},
}
這是我擁有的陣列。
arr = ['translate.en', 'title'];
我想做的是這個,但這不像我預期的那樣作業。
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.
如何values.translate.en使用 獲得價值map()?
uj5u.com熱心網友回復:
你可以使用這個片段。不是最干凈的,但你明白了
arr.map(item => {
let arrItem = item.split('.');
let data = values;
for (i in arrItem) {
data = data[arrItem[i]];
}
return data;
});
uj5u.com熱心網友回復:
您當前的代碼正在執行以下操作:
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 ..'
如果你想做你想做的事,你應該做到以下幾點:
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 ..'
但是,如果可能的話,我建議您values按以下方式構建您的物件:
const values = {
title: {
kr: '???',
en: 'title'
},
body: {
en: 'some texts .. ',
kr: '??? ??? .. ',
},
};
所以只要你知道哪一部分:body或是title必需的,并且你知道你想要得到的語言,就很容易得到它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/454576.html
標籤:javascript 反应 字典
上一篇:在字典中存盤和使用對變數的參考
