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

如何在React Native中筛选数组?提取指定键对应的子数组

根据对象名称获取对应数组内容

给定数组:

let array = [{
  "mobile1": [{
     "screensize": "6.5"
  }]
},
{
  "mobile2": [{
    "screensize": "6.5"
  },
  { 
    "price": "2000"
  }]
}]

需求是获取mobile2对应的全部数组内容,最终结果如下:

let final = [{
  "screensize": "6.5"
},
{
  "price": "2000"
}]

解决方案

可以通过数组的find方法定位到包含目标键名的对象,再提取对应的值:

写法一(可读性强)

const targetKey = "mobile2";
// 找到包含目标键的对象
const targetObj = array.find(item => item.hasOwnProperty(targetKey));
// 提取数组内容,未找到则返回空数组
const final = targetObj ? targetObj[targetKey] : [];

写法二(简洁版)

const final = array.find(item => item.mobile2)?.mobile2 || [];

两种写法都能得到目标数组,简洁版使用了可选链操作符?.,可以避免因找不到目标对象而抛出Cannot read property 'mobile2' of undefined的错误,兼容性要求ES2020及以上环境。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 07:00:57