多独立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 assumesdatais a single object that directly contains thebatmankey. But your data is three separate objects, so this lookup can't find anything.data[0][batman]: Ifdatawas an array,data[0]would be the object containingjoker—which doesn't have abatmankey. Also,batmanisn't wrapped in quotes, so it's treated as a variable instead of a string key. Even if you wrotedata[0]['batman'], it still wouldn't work since the first object has no such key.
内容的提问来源于stack exchange,提问作者Lieutenant Dan
相关产品推荐
相关产品推荐

