I am trying to check in JavaScript if a value from a json is an empty list or not. I tried obviously json.bundleProductSummaries != []. This doesn't work, however this works:
JSON.stringify(json.bundleProductSummaries) != JSON.stringify([])
My json :
{
"bundleProductSummaries": [
]
}
My code :
fs = require('fs')
body = fs.readFileSync('./json.txt',{encoding : 'utf-8'})
// ---- Parsing de body ----
let json = JSON.parse(body);
let colored = null;
if(json.bundleProductSummaries != []){
json = json.bundleProductSummaries[0];
}
Thank you for your future answers ! Syndorik
You need to check length
json.bundleProductSummaries.length === 0
Because in JS
console.log([] === [] )
as they are two different memory reference.
But when two array will evaluate to true ?
When they both the value you're comparing is having same reference
let a = [] console.log(a === a)
You can check the length
of the Array to check if its empty
let obj = { "bundleProductSummaries": [] } console.log(obj.bundleProductSummaries.length === 0)
In you case you can just don't need to compare because you are using it in if
statement and 0
is itself a falsy value.
let obj = { "bundleProductSummaries": [] } if(!obj.bundleProductSummaries.length){ console.log("Array is empty") }
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.