我得到了一个具有以下数据结构的数组:
[
{
_id: 'dgPMHw3ivRSp3wyWe',
content: {
en: [{ content: 'foo', extended: 'bar' }, {...}],
it: [{ content: 'any', extended: 'thing' }, {...}]
},
order: 1,
parent: 'Dn59y87PGhkJXpaiZ'
},
{...}
]
我需要修改此数组,通过选择特定语言的第一个元素来仅获取 content
的字符串值。
因此对于英语,结果应该是:
[
{
_id: 'dgPMHw3ivRSp3wyWe',
content: 'foo',
extended: bar,
order: 1,
parent: 'Dn59y87PGhkJXpaiZ'
}
]
我知道我可以得到字符串
const language = 'en'
array.forEach(doc => {
console.log(doc.content[language][0].content)
console.log(doc.content[language][0].extended)
})
但是我如何替换它才能得到我的结果?
最佳答案
以下是无需列出每个属性的方法:
var array = [{
_id: 'dgPMHw3ivRSp3wyWe',
"content": {
en: {
content: 'foo',
extended: 'bar'
},
it: {
content: 'any',
extended: 'thing'
}
},
order: 1,
parent: 'Dn59y87PGhkJXpaiZ'
}];
const language = "en";
array = array.map(doc => {
doc = Object.assign(doc, doc.content[language]);
return doc;
});
console.log(array);
关于javascript - JS : How to extract nested string of object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47724675/