操作 ajax 响应



我有一个ajax post方法。我从后端获取对象

$.ajax({
        type: "POST",
        url: URL_one,
        data: submitData
}).then(function (response) {
       console.log("Ajax response", response);
   });

当我做一个控制台.log(响应)时;在 POST 方法中,我看到以下数据。

>Object{Info:Array[200]}
      >Info:Array[200]
                >[0-99]  
                      >0:Object
                          name:'Ashley'
                          on_pay: true
                          valid:"0"
                >[100-199]

因此,每个数组都有像上面提到的对象一样,名称,on_pay和有效。我想执行以下操作由于所有on_pay值在我的情况下都是真的,我需要将其转换为假。字符串 0 也有效。我需要将所有值设置为空白而不是 0。

可以做到吗?有人可以对这些有所了解吗?

考虑到您显示的 JSON 结构,以下内容应该可以更改on_pay值:

response.Info.forEach(function(item){
    item.on_pay = false;
});

如果我正确理解了您的问题,response是一个项目数组。 您希望保持这些项不变,但将 on_pay 属性falsevalid转换为空字符串。

您可以使用 Array::map() 来转换每个项目。

/*jslint node:true*/
"use strict";
// I am assuming your response looks something like this
var response = {
    Info: [
        {
            name: "Ashley",
            on_pay: true,
            valid: "0"
        },
        {
            name: "Jim",
            on_pay: true,
            valid: "0"
        },
        {
            name: "John",
            on_pay: true,
            valid: "0"
        }
    ]
};
// This will produce a new variable that will hold the transformed Info array
var fixedResponseInfo = response.Info.map(function (item) {
    item.on_pay = false;
    item.valid = "";
    return item;
});
// This will edit the response.Info array in place
response.Info.forEach(function (item) {
    item.on_pay = false;
    item.valid = "";
});
console.log(fixedResponseInfo);
console.log(response);

这将保留原始响应变量,并生成包含转换后的数组的新变量fixedResponseInfo。 如果您不关心 response 中的数据是否已更改,则可以改用 Array::forEach() 进行迭代。

最新更新