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

多独立JSON对象数据下,如何遍历获取指定batman对象数据?

如何从多个独立JSON对象中获取batman对应的完整对象?

Hey there! Let's break down why your previous attempts didn't work and how to grab that batman object correctly.

First off, a key point: you're working with three separate JSON objects, not a single large object containing all three keys, nor an array of objects. That's exactly why data['batman'] and data[0][batman] didn't give you what you needed.

解决思路

We need to first organize these standalone JSON strings into a traversable structure, then parse each one and look for the object that has the batman key.

具体实现代码

Assuming your raw data exists as a collection of strings, here's how to handle it:

// First, wrap all your standalone JSON strings into an array
const rawData = [
  '{"joker":{"baseMapId":"1536abe5e5504e5db380ccfaa9b6fd8d","customBaseMap":"","zoomn":"5","orient":"0","centLon":"-93.69999999999843","centLat":"38.64999999999935","baseMapLabels":"true"}}',
  '{"batman":{"baseMapId":"1536abe5e5504e5db380ccfaa9b6fd8d","customBaseMap":"","zoomn":"5","orient":"0","centLon":"-93.69999999999843","centLat":"38.64999999999935","baseMapLabels":"true"}}',
  '{"merman":{"baseMapId":"1536abe5e5504e5db380ccfaa9b6fd8d","customBaseMap":"","zoomn":"5","orient":"0","centLon":"-93.69999999999843","centLat":"38.64999999999935","baseMapLabels":"true"}}'
];

// Option 1: Use a loop to find the target
let batmanResult = null;
for (const jsonStr of rawData) {
  const parsedObj = JSON.parse(jsonStr);
  if (parsedObj.hasOwnProperty('batman')) {
    batmanResult = parsedObj;
    break; // Stop searching once we find it
  }
}

// Option 2: A more concise approach with array methods
const batmanResult = rawData
  .map(str => JSON.parse(str))
  .find(obj => obj.hasOwnProperty('batman'));

// Log the result you want
console.log(batmanResult);

为什么之前的尝试失败?

  • data['batman']: This assumes data is a single object that directly contains the batman key. But your data is three separate objects, so this lookup can't find anything.
  • data[0][batman]: If data was an array, data[0] would be the object containing joker—which doesn't have a batman key. Also, batman isn't wrapped in quotes, so it's treated as a variable instead of a string key. Even if you wrote data[0]['batman'], it still wouldn't work since the first object has no such key.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 21:37:39