如何从现有数组提取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
相关产品推荐
相关产品推荐

