Access the properties of a returned data using Nodejs

Viewed 11729

I want to access the age property of a returned Object in Nodejs and also be able to filter through it.

The Returned Oject

{"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, key=4SCsU, age=65, key=q3kG6, age=33, key=MGQpf, age=13, key=Kj6xW, age=14, key=tg2VM, age=30, key=WSnCU, age=24, key=f1Vvz, age=46, key=dOS7A, age=72, key=tDojg, age=82, key=nZyJA, age=48, key=R8JTk, age=29, key=005Ot, age=66, key=HHROm, age=12, key=5yzG8, age=51, key=xMJ5D, age=38, key=TXtVu, age=82, key=Hz38B, age=84, key=WfObU, age=27, key=mmqYB, age=14, key=4Z3Ay, age=62, key=x3B0i, age=55, key=QCiQB, age=72, key=zGtmR, age=66, key=nlIN9, age=8, key=hKalB, age=50, key=Na33O, age=17, key=jMeXm, age=15, key=OO2Mc, age=32, key=hhowx, age=34, key=gLMJf, age=60, key=PblX6, age=66, key=8Vm5W, age=22, key=oZKd6, age=88, key=RXNfQ, age=
{"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 ...

MY CODE

const https = require('https');

https.get('https://coderbyte.com/api/challenges/json/age-counting', (resp) => {
  let {statusCode} = resp
  let contentType = resp.headers['content-type']
  resp.setEncoding('utf-8')
  let data = '';

  // parse json data here...
  resp.on('data', (d) => {
    data += d
    console.log(data)
  })
  resp.on("error", (e) => {
    console.log("error", e)
  })

  //console.log(resp);

});

Please can anyone help with it??

9 Answers

I can now access it with this code, thanks to everyone.

but i wanto to collapse the logs to one integer, can anyone point it out to me?

const https = require('https');

https.get('https://coderbyte.com/api/challenges/json/age-counting', (resp) => {
  let {statusCode} = resp
  let contentType = resp.headers['content-type']
  resp.setEncoding('utf-8')
  let data = '';

  // parse json data here...
  resp.on('data', (d) => {
    data += [d]
  })

    resp.on('end', () => {
    let parsedData = data.split(",")
    .filter(data =>!data.indexOf(" age="))
    .map(data => data.replace(" age=",""))
    .map(data => parseInt(data))
    .filter(data => {
     return (data >= 50);
    }).length
    console.log(parsedData);
  })
  resp.on("error", (e) => {
    console.log("error", e)
  })

  //console.log(resp);

});

Please check if you are looking something like this.

const response =  {"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"}
console.log(response.data.split(",").filter(data => !data.indexOf(" age=")).map(data => data.replace(" age=","")));

This will generate the below result:

 [
"58",
"64",
"47",
"68",
"76",
"79",
"29",
"32"
]

If you want to access the age property you must verify if data is an object.

Because if the type of data is a string, data.age not defined.

You should use

let dataParsed = JSON.parse(data)

Finally, dataParsed.age is defined.

If you have unexpected error use :

JSON.parse(JSON.stringify(data))
const https = require("https");
var fs = require("fs");
const crypto = require("crypto");

https.get("https://coderbyte.com/api/challenges/json/age-counting", (resp) => {
  let { statusCode } = resp;
  let contentType = resp.headers["content-type"];
  resp.setEncoding("utf-8");
  let data = "";

  // parse json data here...
  resp.on("data", (d) => {
    data += [d];
  });
  let array = [];
  sortedArray = [];

  resp.on("end", () => {
    newarray = JSON.parse(data).data.split(",");
    array = [];
    newarray.forEach((val, index) => {
      if (!val.includes(" age=")) {
        keyValue = val.replace(" key=", "");
        keyValue = keyValue.replace("key=", "");
        let age = newarray[index + 1].replace(" age=", "");
        if (age > 32) {
          sortedArray.push([keyValue]);
          array.push({
            [keyValue]: age,
          });
        }
      }
    });
    const writeStream = fs.createWriteStream("output.txt");
    const pathName = writeStream.path;
    sortedArray.forEach((value) => writeStream.write(`${value}\n`));

    // the finish event is emitted when all data has been flushed from the stream
    writeStream.on("finish", () => {
      const fileBuffer = fs.readFileSync("output.txt");
      const hashSum = crypto.createHash("sha256");
      hashSum.update(fileBuffer);
      const hex = hashSum.digest("hex");
      console.log(hex);
    });

    // handle the errors on the write process
    writeStream.on("error", (err) => {
      console.error(`There is an error writing the file ${pathName} => ${err}`);
    });

    // close the stream
    writeStream.end();
  });

  //console.log(resp);
});

If you want to get only the last integer that is the no of age property then you must move your code to 'end' event.

const https = require('https');

  https.get('https://coderbyte.com/api/challenges/json/age-counting', (resp) => {
   let {statusCode} = resp
   let contentType = resp.headers['content-type']
   resp.setEncoding('utf-8')
   let data = '';

  // parse json data here...
  resp.on('data', (d) => {
    data += [d]
  })

  resp.on('end', () => {
    let parsedData = data.split(",")
    .filter(data =>!data.indexOf(" age="))
    .map(data => data.replace(" age=",""))
    .map(data => parseInt(data))
    .filter(data => {
     return (data >= 50);
    }).length
    console.log(parsedData);
  })
  resp.on("error", (e) => {
    console.log("error", e)
  })

  //console.log(resp);

});

This might be your solution:

const https = require('https');

https.get('https://coderbyte.com/api/challenges/json/age-counting', (resp) => {
  let data = ''
    resp.on('data', (chunk) => {
      data+=chunk;
    });
    resp.on('end', () => {
      let jsonData = JSON.parse(data.toString());
      let actualData = jsonData.data;
      let arr1 = actualData.split(", ");
      let totalCount = 0;
      for(let i = 0; i < arr1.length; i++){
        let item = arr1[i];
        if(item.indexOf('age=') !== -1){
          let age = item.split('=');
          if(parseInt(age[1]) >= 50) {
            totalCount++;
          }
        }
      }
      console.log(totalCount);
    })
});

Source: https://amudalvi.blogspot.com/p/coderbyte-node-js-age-counting.html

In Swift Language I was try. I was decode the data then convert into json object.

struct DataObject: Decodable {
let data: String
}


let jsonData = JSON.data(using: .utf8)!
let dataObject: DataObject = try! JSONDecoder().decode(DataObject.self, from: jsonData)
 // print(dataObject.data)
var count = 0
for item in dataObject.data.split(separator: ","){
let age = item.split(separator: "=")
let stringAge =  age[0]

if(stringAge == " age"){
    //  print("String agae", stringAge)
     let ageInt = age[1]
    //  print("String agae Int ", ageInt)
     if Int(String(ageInt))! >= 50){
        count = count + 1 
     }
    // print("age and key",age)
}
}

Here's my take on this one

const https = require('https');

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

  resp.on('data', (chunk) => {
    data = data += chunk
  })

  resp.on('end',  () => {
    let parsedData = JSON.parse(data.toString()).data
    let arrayData = parsedData.split(", ")

    let ageArray = [];
    for (i = 0; i < arrayData.length; i++) {
      if (i%2 === 1) {
        ageArray.push(Math.floor(arrayData[i].slice(4)))
      }
    }

    let filteredArray = ageArray.filter((item) => {
      return item >= 50
    })

    console.log(filteredArray.length)
  })
});

You can manipulate your output array until you only get the only part that you really need, which are the numbers. Then you can just easily filter that array by value and return the length of it.

const response =  {"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"}
const count = response.data.split(",").map(value=>value.split("=")).filter(value=> value[0]===" age").reduce((cumulative,current)=>{if(Number(current[1])>=50){ return cumulative+1}else{return cumulative}},0);
console.log(count)
Related