javascript - 提取一个对象数组内的属性,该对象数组位于另一个对象数组内,并将结果作为字符串数组

标签 javascript typescript

我有一个具有以下结构的 TypeScript 对象数组:

const surveyResponses: any[] = [
  {createdAt: new Date(), responses: [{questionId: 'input1', response: 'Bla'}]},
  {createdAt: new Date(), responses: [{questionId: 'input1', response: 'Blo'}]}
];

我想提取 responses 数组中的 response 属性,并将它们作为单个字符串数组。

预期结果:['Bla', 'Blo']

我尝试遵循以下建议:

  1. From an array of objects, extract value of a property as array
  2. 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/

相关文章:

java - 使用 map 时如何从 Controller 获取数据

javascript - Angular 7 中静态内容的通配符路由

node.js - Typescript 编译器选择错误的重载

Angular react 形式 : valueChanges doesn't work as expected

typescript - 如何使用 TypeORM 在 React-Native 中处理 SQLite 迁移?

javascript - 如何使用 jQuery/AJAX 在 HTML div 中加载 html 页面内容?

javascript - 是否有利用 jQuery 的 JavaScript 所见即所得?

javascript - 有什么简单的方法可以将这个特定的数字形式转换为 moment.js 中的 Moment 吗?

javascript - 如何改变threejs圆柱体的厚度

javascript - 在 Angular 中链接可观察订阅的最佳方式?