如何用一行代码过滤和修改对象数组?

How to filter and modify an array of objects with a single line of code?

我的数据库中有以下对象数组:

dataFromDB = [
  { src: 'stringWithSource1',
    selected: true
  },
  { src: 'stringWithSource2',
    selected: false
  },
  { src: 'stringWithSource3',
    selected: true
  },
  AND SO ON...
];

当我从数据库中获取它时,我需要在客户端的 state 中存储 必须是一个字符串数组 ,其中包含 只有 src 属性 个对象是 selected: true.

示例:

myState = [
  'stringWithSource1',
  'stringWithSource3',
  AND SO ON...
]

问题

我分配的行如下(见下面的代码):

我试过了,但这不起作用,因为我将未选择的 src 保留为 null 而不是跳过它们。

setProductDetails({
  // ... other properties,
  images: dataFromDB.images.map((item) => {
    return item.selected ? item.src : null;
  }
});

我怎样才能像这样在一行中实现这种行为?我知道我可以创建一个辅助变量并处理它。但在这种情况下,我想要一条单线。这可能吗?感觉应该同时过滤和映射?

您需要两部分,因为过滤不映射值,而是映射原始项。

您可以按 selected 过滤,然后映射 src

images: dataFromDB.images
    .filter(({ selected }) => selected)
    .map(({ src }) => src)