I have a JSON like this:
{
"livingroom": [],
"bedroom": [],
"study": [
{
"name": "s0",
"thumbnail": "/[email protected]/Cuiti/study/web/螢幕快照 2016-03-29 下午2.12.32.png",
"web": ".tw/Cuiti/study/web/201603292.12.32.png"
}
],
"outdoor": [],
"other": [],
"id": "-KE5spXGRjC_9WSIh_eN",
"name": "Cuiti",
"categoryCount": 1,
"panoramaCount": 1
}
I want to only exclude the []
s. I tried value.length > 0
but that throws an error because some of the values aren't arrays.
What's the best solution?
I have a JSON like this:
{
"livingroom": [],
"bedroom": [],
"study": [
{
"name": "s0",
"thumbnail": "https://storage.googleapis./peterbucket/0/small_istagingViewer/[email protected]/Cuiti/study/web/螢幕快照 2016-03-29 下午2.12.32.png",
"web": "https://storage.googleapis./peterbucket/istagingViewer/sigstaging..tw/Cuiti/study/web/201603292.12.32.png"
}
],
"outdoor": [],
"other": [],
"id": "-KE5spXGRjC_9WSIh_eN",
"name": "Cuiti",
"categoryCount": 1,
"panoramaCount": 1
}
I want to only exclude the []
s. I tried value.length > 0
but that throws an error because some of the values aren't arrays.
What's the best solution?
Share Improve this question asked Mar 30, 2016 at 10:44 alexalex 7,61115 gold badges53 silver badges79 bronze badges 5- Possible duplicate of stackoverflow./questions/679915/… – Kalpesh Singh Commented Mar 30, 2016 at 10:46
-
if (value.length && value.length > 0) // code here
– jonny Commented Mar 30, 2016 at 10:46 -
@JonathanBrooks i'm still getting the error:
Error when evaluating expression "keyIsVisible($key) && (value.length && value.length > 0)". vue.mon.js?e881:3386 Uncaught TypeError: Cannot read property 'length' of undefined
– alex Commented Mar 30, 2016 at 10:48 -
Oh I see, you'll have to check the value isn't undefined instead then. Like
if(typeof value !== "undefined") // continue here
– jonny Commented Mar 30, 2016 at 10:49 - use if(typeof(temp.livingroom) ==! undefined) ... before checking for length – damitj07 Commented Mar 30, 2016 at 10:50
4 Answers
Reset to default 2First of all, your sample is not JSON, it's a Javascript Object. In order to remove empty arrays from this object, you can simply check it like this
for(var key in yourObject){
var value = yourObject[key];
if(Array.isArray(value) && value.length === 0){
delete yourObject[key];
}
}
You can use Array.isArray()
to check if something is an array:
if (Array.isArray(value) && value.length > 0) { }
And use this polyfill from MDN if needed:
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
You can use constructor
property to check whether value is array or not and then check length of value
for(var key in items){
var value=items[key];
if(value.constructor===Array && value.length === 0){
delete items[key];
}
}
You can use instanceof operator
function isArray(value) {
return value instanceof Array;
}