简体   繁体   中英

Looping through a JSON array and replacing the values if they are NULL

I have an array of JSON coming from my controller

<%= raw @visits %>

在此处输入图片说明

I simply want to loop through this, and if the "name" is null then replace it with the string "Unknown". Currently this fails.

var withNull = <%= raw @visits %>;

var noNull = $.each(withNull, function(obj) {
    if(obj.name ==  null) {
        obj.name = "Unknown";
    }
});

Use

$.each(withNull, function(idx, obj) {

The parameters to jQuery's $.each callback are in "backward" order. It passes the index first, then the element.

Prefer to use

withNull.forEach(function(obj) {

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