te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Access the properties of a returned data using Nodejs - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Access the properties of a returned data using Nodejs - Stack Overflow

programmeradmin3浏览0评论

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('', (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??

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./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??

Share Improve this question edited Aug 6, 2021 at 19:07 Chandan Jee 5,9004 gold badges17 silver badges24 bronze badges asked Jun 24, 2020 at 9:01 ihugba chinemerem Kizitoihugba chinemerem Kizito 731 gold badge1 silver badge7 bronze badges
Add a ment  | 

9 Answers 9

Reset to default 3

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

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

});

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)
}
}
const https = require("https");
var fs = require("fs");
const crypto = require("crypto");

https.get("https://coderbyte./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);
});

This might be your solution:

const https = require('https');

https.get('https://coderbyte./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./p/coderbyte-node-js-age-counting.html

Here's my take on this one

const https = require('https');

https.get('https://coderbyte./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)
发布评论

评论列表(0)

  1. 暂无评论