Newbie Developer
Newbie Developer

Reputation: 23

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?? Any code Snippet for javaScript would be lovely. Cudos.

Upvotes: 0

Views: 106

Answers (4)

Brewal
Brewal

Reputation: 8189

You can use the map function to get a one liner :

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);

Upvotes: 2

Lakshaya U.
Lakshaya U.

Reputation: 1181

Use 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);

Upvotes: 0

David
David

Reputation: 864

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
    }
}

Upvotes: 0

Deepak
Deepak

Reputation: 2742

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. 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)

Upvotes: 0

Related Questions