2

I have a JSON like this:

{
  "livingroom": [],
  "bedroom": [],
  "study": [
    {
      "name": "s0",
      "thumbnail": "https://storage.googleapis.com/peterbucket/0/small_istagingViewer/sig@staging.com.tw/Cuiti/study/web/螢幕快照 2016-03-29 下午2.12.32.png",
      "web": "https://storage.googleapis.com/peterbucket/istagingViewer/sigstaging.com.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?

alex
  • 7,111
  • 15
  • 50
  • 77
  • Possible duplicate of http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object – Kalpesh Singh Mar 30 '16 at 10:46
  • `if (value.length && value.length > 0) // code here` – jonny Mar 30 '16 at 10:46
  • @JonathanBrooks i'm still getting the error: `Error when evaluating expression "keyIsVisible($key) && (value.length && value.length > 0)". vue.common.js?e881:3386 Uncaught TypeError: Cannot read property 'length' of undefined` – alex Mar 30 '16 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 Mar 30 '16 at 10:49
  • use if(typeof(temp.livingroom) ==! undefined) ... before checking for length – damitj07 Mar 30 '16 at 10:50

4 Answers4

2

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]';
    };
}
Joakim Johansson
  • 3,196
  • 1
  • 27
  • 43
2

First 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];
    }
}
Lewis
  • 14,132
  • 12
  • 66
  • 87
1

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];
    }
}
Joakim Johansson
  • 3,196
  • 1
  • 27
  • 43
Shoaib
  • 822
  • 1
  • 15
  • 27
1

You can use instanceof operator

function isArray(value) {
    return value instanceof Array;
}
Slavik
  • 6,647
  • 3
  • 15
  • 18