简体   繁体   English

如何循环通过 JSON 对象和 Arrays 内部

[英]How to Loop through JSON Objects having Objects and Arrays Inside

 let mything = { "holders": [{ "address": "0xbe0eb53f46cd790cd13851d5eff43d12404d33e8", "balance": 8.623839536582375e24, "share": 52.02 }, { "address": "0xf977814e90da44bfa03b6295a0616a897441acec", "balance": 4.5e24, "share": 27.14 }] }; let m = Object.entries(mything); console.log(m);

The above is a json data, stored in a file, now what I want to do is to loop over this whole file which has 2000 of such entries, get just the address part of each entry and append it in a url, so how would I do the looping part??上面是一个 json 数据,存储在一个文件中,现在我要做的是循环整个文件,它有 2000 个这样的条目,只获取每个条目的地址部分和 append 它在 Z572D4E4E421E5E6B718A我做循环部分?? Any code Snippet for javaScript would be lovely. javaScript 的任何代码片段都会很可爱。 Cudos.谢邀。

You can use the map function to get a one liner:您可以使用map function 获得一个衬垫:

 const data = {"holders": [{ "address": "0xbe0eb53f46cd790cd13851d5eff43d12404d33e8", "balance": 8.623839536582375e24, "share": 52.02 },{ "address": "0xf977814e90da44bfa03b6295a0616a897441acec", "balance": 4.5e24, "share": 27.14 }]}; const url = "https://my.url/"; const urls = data.holders.map(holder => `${url}${holder.address}`); console.log(urls);

Since holders object is an array, you can loop over it like below, and make use of the address like constructing the URL as per your logic inside the loop.由于holders object 是一个数组,因此您可以像下面一样循环它,并根据循环内的逻辑使用地址,如构造 URL 。 Here's the example of storing the addresses in an array:这是将地址存储在数组中的示例:

 var original = { "holders": [{ "address": "0xbe0eb53f46cd790cd13851d5eff43d12404d33e8", "balance": 8.623839536582375e24, "share": 52.02 }, { "address": "0xf977814e90da44bfa03b6295a0616a897441acec", "balance": 4.5e24, "share": 27.14 }] }; var addresses = []; for (let holder of original.holders) { addresses.push(holder.address); } console.log(addresses)

const data = {"holders": [{ "address": "0xbe0eb53f46cd790cd13851d5eff43d12404d33e8", "balance": 8.623839536582375e24, "share": 52.02 },{ "address": "0xf977814e90da44bfa03b6295a0616a897441acec", "balance": 4.5e24, "share": 27.14 }]}; for(const obj of Object.values(data)) { for(const arr of obj) { // Your code } }

Use Array.prototype.map .使用Array.prototype.map

 const holders = [{ "address": "0xbe0eb53f46cd790cd13851d5eff43d12404d33e8", "balance": 8.623839536582375e24, "share": 52.02 }, { "address": "0xf977814e90da44bfa03b6295a0616a897441acec", "balance": 4.5e24, "share": 27.14 }]; const addresses = holders.map((holder) => holder.address); console.log(addresses);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM