jQuery循环遍历JSON多维数组

6jygbczu  于 2023-04-11  发布在  jQuery
关注(0)|答案(3)|浏览(117)

我有一个JSON数组被返回,我想通过它来循环显示表中的数据:

{"confirmed":"362.53","not_confirmed":"9,403.87","payouts":{"confirmed":{"2023-04-05":36253},"submitted":{"2023-04-12":900,"2023-04-11":9600},"pending_submission":{"2023-04-13":897694,"2023-05-04":32193}}}

我尝试在 AJAX 调用中使用这个for循环,但在控制台中看到的只是Object object

$.ajax({
    type: "GET",
    url: ""
    dataType: 'json',
    success: function(data) {
        for(var i in data.payouts) {
            console.log(data.payouts[i]);
        }
    }
});
bvuwiixz

bvuwiixz1#

在我看来,你的代码工作?

let object = {"confirmed":"362.53","not_confirmed":"9,403.87","payouts":{"confirmed":{"2023-04-05":36253},"submitted":{"2023-04-12":900,"2023-04-11":9600},"pending_submission":{"2023-04-13":897694,"2023-05-04":32193}}}

for (var key in object.payouts) {
  console.log('Key:', key)
  console.log(object.payouts[key])
}
e0bqpujr

e0bqpujr2#

$.each()函数中,代码为支出的每个嵌套属性向控制台记录一条消息,具体来说,它记录该嵌套对象的confirmed属性的值。

尝试下面的片段

let data = { "confirmed": "362.53", "not_confirmed": "9,403.87", "payouts": { "confirmed": { "2023-04-05": 36253 }, "submitted": { "2023-04-12": 900, "2023-04-11": 9600 }, "pending_submission": { "2023-04-13": 897694, "2023-05-04": 32193 } } };
$.each(data, function (index, element) {
    if (index == 'payouts') {
        console.log(element);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
o7jaxewo

o7jaxewo3#

data.payouts不是一个数组,它是一个包含一组键和值的对象。要迭代对象,可以使用Object类中的方法(docs here:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)。
要迭代键和值,在每次迭代中获取它们,可以像这样使用Object.entries()

const data = {"confirmed":"362.53","not_confirmed":"9,403.87","payouts":{"confirmed":{"2023-04-05":36253},"submitted":{"2023-04-12":900,"2023-04-11":9600},"pending_submission":{"2023-04-13":897694,"2023-05-04":32193}}};

for (const [key, value] of Object.entries(data.payouts)) {
  console.log(key, "=>", value);
}

我使用for..of来获取值,而不是使用for..in并获取Object.entries()方法返回的数组中每个项的索引。
请注意,每个条目中的值也是一个对象,因此如果要处理它们,需要对每个条目使用相同的逻辑。

相关问题