node.jsbackend

NodeJS debugging coderbyte Task


node.js debugging json data in the javascript file, you have a program that performs a get request on the route https://coderbyte.com/api/challenges/json/age-counting which contains a data key and the value is a string which contains items in the format: key=string, age=integer. your goal is to print out the key id's between indices 10 and 15 in string format (e.g. q3kg6,mgqpf,tg2vm,...). the program provided already parses the data and loops through each item, but you need to figure out how to fix it so that it correctly populates keyarray with only key id's. here is code given by coderbyte.

const https = require('https');

https.get('https://coderbyte.com/api/challenges/json/age-counting', (resp) => {

let content = '';

// push data character by character to "content" variable
resp.on('data', (c) => content += c);

// when finished reading all data, parse it for what we need now
resp.on('end', () => {

let jsonContent = JSON.parse(content);
let jsonContentArray = jsonContent.data.split(',');
let keyArray = [];

for (let i = 0; i < jsonContentArray.length; i++) {
  let keySplit = jsonContentArray[i].trim().split('=');
  keyArray.push(keySplit[1]);
}

console.log(keyArray.toString());
});

});



Solution

  • const https = require('https');
    
    https.get('https://coderbyte.com/api/challenges/json/age-counting', (resp) => {
      let content = '';
    
      // push data character by character to "content" variable
      resp.on('data', (c) => content += c);
    
      // when finished reading all data, parse it for what we need now
      resp.on('end', () => {
        let jsonContent = JSON.parse(content);
        let jsonContentArray = jsonContent.data.split(',');
        let keyArray = [];
        console.log(jsonContentArray.length);
        // Traversing over the json content array and checking only for keys while ignoring the age.
        for (let i = 0; i < jsonContentArray.length; i+=2) {
          // extracting only the keys by triming the white space and splitting the data by "=" and taking the first character from the array.
          let key = jsonContentArray[i].trim().split('=')[1];
          // Now pushing only the 10*2 for getting the keys and ignoring the age. If you look into the json you get a better understanding.
    // Here is an eg of json considered.
    // data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47, key=0Sr4C, age=68, key=CGEqo, age=76, key=IxKVQ, age=79, key=eD221, age=29, key=XZbHV, age=32, key=k1SN5, age=88, .....etc
          if (i>=20 && i< 30) {
            keyArray.push(key);
          }
        }
    
        console.log(keyArray);
      });
    });