简体   繁体   English

jQuery.each() 不迭代 object

[英]jQuery.each() doesn't iterate object

Using latest jQuery 3.6.0 I can't figure out why the object is not iterated.使用最新的 jQuery 3.6.0 我无法弄清楚为什么 object 没有被迭代。

json = [{"id":9,"brand_id":"","supplier_id":"","code":"","sku":"item","mpn":"","gtin":"","taric":"","image":"","quantity":100,"quantity_unit_id":1,"ordered":0,"weight":0,"weight_unit":"kg","length":0,"width":0,"height":0,"length_unit":"cm"}];

$.each(json, function(i) {
  $.each(json[i], function(key, value) {
    console.log(key, value);
    alert('Does not come this far');
  });
});

This object however works:然而,这个 object 有效:

json = [{"foo":"bar", "this": "that"}];

Can anyone spot the obvious?任何人都可以发现明显的吗? https://jsfiddle.net/qnbwm0ej/ https://jsfiddle.net/qnbwm0ej/

Object.keys() Object.keys()

+Edited for the real "value":) +为真正的“价值”而编辑:)

    json = [{"id":9,"brand_id":"","supplier_id":"","code":"","sku":"item","mpn":"","gtin":"","taric":"","image":"","quantity":100,"quantity_unit_id":1,"ordered":0,"weight":0,"weight_unit":"kg","length":0,"width":0,"height":0,"length_unit":"cm"}];

$.each(json, function(i) {
  console.log(json[i]);

  $.each(Object.keys(json[i]), function(key, value) {
    console.log(value, json[i][value]);
  });
});

++Edit ++编辑

It's not going to iterate each key-value because you added property "length":0 .它不会迭代每个键值,因为您添加了属性"length":0 If you add a "length":0 property to the second object you posted, it won't work just like the first object.如果您将"length":0属性添加到您发布的第二个 object,它将不会像第一个 object 那样工作。 You can check why and how the jquery.each works from here line 238您可以从此处的第 238 行检查 jquery.each 的工作原理和方式

This is some tests for the custom length property in objects.是对对象中自定义length属性的一些测试。

Convert all the integer value to string as below.将所有 integer 值转换为字符串,如下所示。

json = [{"id":"9","brand_id":"","supplier_id":"","code":"","sku":"item","mpn":"","gtin":"","taric":"","image":"","quantity":"100","quantity_unit_id":"1","ordered":"0","weight":"0","weight_unit":"kg","length":"0","width":"0","height":"0","length_unit":"cm"}];

$.each(json, function(index,jsonObject){
    console.log(jsonObject);
    $.each(jsonObject, function(key,val){
        console.log(key, val);
    });
});

If you do not want to change the data.如果您不想更改数据。 Please use for...in loop.请使用 for...in 循环。

json = [{"id":9,"brand_id":"","supplier_id":"","code":"","sku":"item","mpn":"","gtin":"","taric":"","image":"","quantity":100,"quantity_unit_id":1,"ordered":0,"weight":0,"weight_unit":"kg","length":0,"width":0,"height":0,"length_unit":"cm"}];
$.each(json, function(index,jsonObject){
    console.log(jsonObject);
  for(var key in jsonObject) {
     console.log(key, jsonObject[key]); 
    } 
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM