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

React Native中如何从嵌套数组提取指定字段至新数组?

解决嵌套数组提取weight字段的问题

你的嵌套数组结构是外层数组包含一个子数组,子数组内是多个Todo对象。之前的写法只取到第一个weight的原因是:外层map仅遍历外层数组的元素(这里只有1个),b是子数组,i是外层索引(0),b[i]就只指向子数组的第一个对象,所以结果只有一个值。

以下是几种可行的解决方法:

情况1:外层数组固定只有一个子数组

直接获取外层数组的第一个元素,再对其内部对象做map提取weight:

const weights = arrayname[0].map(item => item.weight);
// 输出:[135, 135]

情况2:外层数组可能包含多个子数组

如果后续外层数组可能有多个子数组,需要先将嵌套数组扁平化,再提取weight:

方法1:使用flat()扁平化

const weights = arrayname.flat().map(item => item.weight);
// 输出:[135, 135](若有更多子数组也会统一提取)

方法2:使用reduce()手动合并

const weights = arrayname.reduce((result, subArray) => {
  return result.concat(subArray.map(item => item.weight));
}, []);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 22:03:17