简体   繁体   中英

How to convert JSON property array to Array of strings Object in node.js?

I currently have the following JSON:

{
  "Id": ["1", "2"],
  "Settings": [{ "Key": "IgnitionOn", "Value": "true" }]
}

I want to be able to access Id and convert it to an Array of strings in node.js. Namely, what I want to do is access Id using req.body.Id . This works when Id is just a string. If I try to access req.body.Id currently, I get it to be undefined. I have also tried JSON.parse(req.body.Id) and JSON.stringify(req.body.Id) but in both approaches, the Ids are still undefined. Given my req body above, any suggestions on how I can create an instance of an array that is precisely the Id array in the body?

Any help will be much appreciated!

You can parse this JSON to get an object:

const result = JSON.pasrse(req.body)
const id = result.id;

If you body is in JSON, you will need to parse then entire body with JSON.parse(req.body) before accessing the .Id field

let req = {
    body: `{
        "Id": ["1","2"],
        "Settings": [{"Key": "IgnitionOn", "Value": "true"}]
        }`
}
let body = JSON.parse(req.body)
let ids = body.Id
console.log(ids)
// [ '1', '2' ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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