我有一个具有以下结构的 TypeScript 对象数组:
const surveyResponses: any[] = [
{createdAt: new Date(), responses: [{questionId: 'input1', response: 'Bla'}]},
{createdAt: new Date(), responses: [{questionId: 'input1', response: 'Blo'}]}
];
我想提取 responses
数组中的 response
属性,并将它们作为单个字符串数组。
预期结果:['Bla', 'Blo']
我尝试遵循以下建议:
- From an array of objects, extract value of a property as array
- Returning only certain properties from an array of objects in Javascript
我尝试使用reduce
但没有运气:
responses.reduce((a, o) => (o.responses.map(r => r.response) && a.push(o.responses.map(r => r.response)), a), []);
我尝试使用map
但没有成功:
responses.map(r => r.responses).map(r => r.map(r => r.response));
Result: [["Bla"], ["Blo"]]
如有任何帮助,我们将不胜感激。
最佳答案
使用flatMap
获取responses
数组,获取它们的response
字符串,然后组合它们:
const surveyResponses = [
{createdAt: new Date(), responses: [{questionId: 'input1', response: 'Bla'}]},
{createdAt: new Date(), responses: [{questionId: 'input1', response: 'Blo'}]}
];
const result = surveyResponses.flatMap(
item => item.responses.map(
({ response }) => response
)
);
console.log(result);
另请注意,使用 any
会破坏使用 TypeScript 的全部意义,因为它实际上禁用了该表达式的类型检查。如果可能的话,要么让 TS 自动推断表达式的类型,要么在需要时自己手动指示类型。 (这样的话,TS可以自动推断出surveyResponses
的类型就可以了)
如果你不能使用flatMap
,你可以展开成concat:
const surveyResponses = [
{createdAt: new Date(), responses: [{questionId: 'input1', response: 'Bla'}]},
{createdAt: new Date(), responses: [{questionId: 'input1', response: 'Blo'}]}
];
const result = [].concat(...surveyResponses.map(
item => item.responses.map(
({ response }) => response
)
));
console.log(result);
关于javascript - 提取一个对象数组内的属性,该对象数组位于另一个对象数组内,并将结果作为字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64949550/