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

JSON字符串转可查询Object或Array的实现方案咨询

实现方案

你可以将两组数据按索引配对存储为对象数组,再配套简单的查询方法即可满足需求,具体实现如下:

生成目标数组

// 先把原始的逗号分隔值转成数组
const a = 'apple,car,earth'.split(',')
const b = 'fruit,vehicle,planet'.split(',')

// 按索引配对生成映射数组
const mappingArray = a.map((key, idx) => ({
  name: key,
  type: b[idx]
}))

最终生成的mappingArray结构为:

[
  { name: 'apple', type: 'fruit' },
  { name: 'car', type: 'vehicle' },
  { name: 'earth', type: 'planet' }
]

实现查询功能

封装查询方法即可实现指定关键词返回对应值的效果:

function getType(name) {
  const res = mappingArray.find(item => item.name === name)
  return res ? res.type : undefined
}

// 测试效果
getType('apple') // 返回 fruit
getType('car') // 返回 vehicle
getType('earth') // 返回 planet

如果需要更高的查询效率,也可以基于上述数组生成Map结构:

const mappingMap = new Map(mappingArray.map(item => [item.name, item.type]))
mappingMap.get('apple') // 直接返回 fruit

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:57:00