JS how to tell if an object {} is an empty object, without any attributes

Source: Internet
Author: User

JS how to tell if an object {} is an empty object, without any attributes

The previous time with JS wrote a similar "Angularjs" for data binding things, the function is relatively simple,

Usually it should come in an array of ArrayList JSON objects,

But sometimes a JSON object is returned through an Ajax method call, not an array!

In order to be compatible with this scenario, the following code is used:

if (typeof model.rows = = = = "Object" &&! Model.rows instanceof Array) {model.rows = [model.rows];}
This code found a bug in the process of later use, that is, when
Model.rows = {};
, it is still treated as a valid object for data binding, and it is conceivable that all data is empty.

Solution:

So how do we solve this problem?

The first habit is to search first, but the results are DOM-related, passable!

This reminds me of the way I wrote the properties of the JS object, which can be used here!

The code is as follows:

if (typeof model.rows = = = = "Object" &&! Model.rows instanceof Array) {var hasprop = False;for (var prop in model.rows) {hasprop = True;break;} if (hasprop) {model.rows = [model.rows];} Else{throw "Model.rows is empty object"; return false;}}
The code is simple and does not write comments.



JS how to tell if an object {} is an empty object, without any attributes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.