You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从现有数组提取fileUrl创建新数组?map/filter该选哪个?

方案选择:使用map方法

你需要将原数组中的每个对象转换为对应的fileUrl值以生成新数组,这种元素转换场景最适合用map方法:

  • filter方法的作用是筛选数组中符合条件的元素,返回的是原结构的对象(不会改变元素的类型/结构),不符合你的需求;
  • map方法的核心就是遍历数组,对每个元素执行转换逻辑并返回新元素,正好匹配“提取每个对象的fileUrl字段”的需求。

代码示例

const originalArray = [
  {
    fileName: "test.pdf",
    fileUrl: "https://test-url1.com/test.pdf",
    isDeleted: true
  },
  {
    fileName: "test.pdf",
    fileUrl: "https://test-url1.com/test.pdf",
    isDeleted: true
  }
];

// 提取所有fileUrl
const fileUrls = originalArray.map(item => item.fileUrl);
console.log(fileUrls); 
// 输出:["https://test-url1.com/test.pdf", "https://test-url1.com/test.pdf"]

拓展:如果需要去重

如果你的场景需要移除重复的fileUrl,可以结合Set实现:

const uniqueFileUrls = [...new Set(originalArray.map(item => item.fileUrl))];
console.log(uniqueFileUrls);
// 输出:["https://test-url1.com/test.pdf"]

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 18:12:36