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

如何将对象数组转为仅含name属性值的数组?含.includes()用法确认

解决方案:提取name数组并使用.includes()检查元素存在性

1. 将对象数组转为仅含name属性的数组

你可以用数组的map()方法提取每个对象的name属性,快速生成目标数组:

// 假设fetchedData是从JSON Server获取到的完整数据对象
const namesArray = fetchedData.savedexercises.map(exercise => exercise.name);

这段代码会遍历savedexercises数组里的每个对象,提取每个对象的name值组成新数组,最终结果为:

["all fours squad stretch", "ankle circles", "arm slingers hanging bent knee legs"]

2. 关于.includes()的正确用法

你之前的理解有偏差:.includes()是数组实例的方法,并非以数组为第一个参数。正确调用方式是直接在目标数组上调用,传入要搜索的元素作为参数:

// 检查指定运动名称是否存在
const isExerciseSaved = namesArray.includes("ankle circles");
// 此例中会返回true,因为该名称在数组内

如果不想额外生成name数组,也可以直接在原对象数组上用some()方法检查:

const isExerciseSaved = fetchedData.savedexercises.some(exercise => exercise.name === "ankle circles");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:46:01