如果对象内的数组内容为null,如何将其设置为false?

时间:2014-07-22 06:26:14

标签: javascript

我使用以下内容获取一些数据并将其加载到对象中:

test.qs = data; 

对象qs看起来像这样:

[
 {"answer":null,
  "answered":true,
  // many more fields here
  "answers":{"correct":null,"response":null}},
 {"answer":null,
  "answered":true,
  // many more fields here
  "answers":{"correct":null,"response":null}}
]

如何才能使数组中的响应值为null,然后将其更改为false?

3 个答案:

答案 0 :(得分:1)

var x=[
 {"answer":null,
  "answered":true,
  // many more fields here
  "answers":{"correct":null,"response":null}},
 {"answer":null,
  "answered":true,
  // many more fields here
  "answers":{"correct":null,"response":null}}
];
var string=JSON.stringify(x).toString().replace(/\:null/g, ":false");
var json=jQuery.parseJSON(string);

这会将所有null变为false

答案 1 :(得分:0)

试试这个:

$(test.qs).each(function () {
  $(this).each(function (i) {
    for(var props in this) {
      if(test.qs[i][props] == null)
        test.qs[i][props] = false;
    }
  });
});

注意:

你需要jQuery来执行这个代码+取决于你在哪里修改代码,它应该是全局可用的,所以如果代码没有工作,那么在你声明变量的地方添加下一个:

window.test = test;

答案 2 :(得分:0)

据我所知:你想改变"响应"的价值。如果它具有值" null"则为false。假设您的Array中的每个对象具有相同的结构,那么它应该起作用:

for(var i = 0; i < test.qs.length; ++i)
{
    if(test.qs[i]["answers"]["response"] == null)
    {
        test.qs[i]["answers"]["response"] = false;
    }
}