循环访问json键以检查其值是否为空

时间:2015-02-05 06:53:47

标签: jquery json performance

我有这个json对象。 Json键remarksaddress为空。如果它为空,则json在提取json时打印undefine。但我想用-符号替换空json。我知道我可以使用:

 if(msg.hasOwnProperty('remarks')== ""){
        alert("A");
   }

但是如何循环遍历所有键并检查它是否为空并替换为-而不是单独检查。

[
{
    "id": "224",
    "booking_id": "1",
    "room_type": null,
    "no_of_rooms_booked": null,
    "check_in_date": "2014-12-23",
    "check_out_date": "2014-12-24",
    "room_id": "93",
    "hotel_id": "9",
    "status": "1",
    "user_id": "15",
    "payment_type": "",
    "payment_status": "",
    "hotelname": "sample hotel",
    "hoteladdress": "sample address",
    "hotelcontact": "056533977",
    "Id": "224",
    "full_name": "Hom Nath Bagale",
    "address": "",
    "occupation": "Student",
    "nationality": "Nepali",
    "contact_no": "9845214140",
    "email": "bhomnath@salyani.com.np",
    "remarks": "",
    "total_amount": "5000",
    "child": "0",
    "adult": "1",
    "verification_code": null,
    "roomname": "sample room2",
    "roomprice": "1.5",
    "roomdescription": "this is for demo",
    "roomimage": "2.jpg"
}]

4 个答案:

答案 0 :(得分:5)

试试这个

data.forEach(function (el) {
  Object.keys(el).forEach(function (property) {
    if (el[property] === '') {
      el[property] = '-';
    }
  });
});

Example

  

Object.keys() - 返回给定对象的数组   可枚举的属性

答案 1 :(得分:3)

  var msg=
    {
        "id": "224",
        "booking_id": "1",
        "room_type": "",
        "roomimage": "2.jpg"
    };

 $.each(msg, function(k, v) {
         if(v===""){
           alert(k + ' is empty' + v);  
           //do actions
         }else{
            alert(k + ' is ' + v);
          }
    });

DEMO

答案 2 :(得分:1)

您可以使用for...in循环遍历每个属性,例如

for (var key in msg) {
    if (msg.hasOwnProperty(key)) {
        if (msg[key] === '') {
            msg[key] = '-'
        }
    }
}

由于您使用过jQuery,您还可以使用{/ 3}}方法,如

$.each(array, function (i, msg) {
    $.each(msg, function (key, value) {
        if (value === '') {
            msg[key] = '-'
        }
    })
});

答案 3 :(得分:0)

下面我提供了2个函数,第一个,其中可以处理整个json 第二个更简单的一个,你必须传递数组中的特定元素(因为你知道你寻找的键只能在第一个元素中使用数组)。

这两种解决方案的特色他们不会修改(改变)传递给他们的原始json

var sampleJson = [{
  "id": "224",
  "booking_id": "1",
  "remarks": "",
  "address": "",
}];

var newJson = getNonEmptyArry(sampleJson);
var newObj = getNonEmptyObj(sampleJson[0]);

console.log('newJson: ' + JSON.stringify(newJson));
console.log('newObj: ' + JSON.stringify(newObj));
console.log('Original Json ' + JSON.stringify(sampleJson));

function getNonEmptyArry(json) {
  var cpyJson = JSON.parse(JSON.stringify(json));
  cpyJson.forEach(obj => {
    Object.keys(obj).forEach(key => {
      if (obj[key] === '') {
        obj[key] = '-';
      }
    });
  });
  return cpyJson;
};

function getNonEmptyObj(obj) {
  var obj = JSON.parse(JSON.stringify(obj));
  Object.keys(obj).forEach(key => {
    if (obj[key] === '') {
      obj[key] = '-';
    }
  });
  return obj;
};
相关问题