【问题标题】:Print jsonp object properties with a loop使用循环打印 jsonp 对象属性
【发布时间】:2017-01-09 16:19:12
【问题描述】:

我通过 jsonp 获取以下对象。这是结构:

     "item1": {
        "child1": {
            "nr": 123,
            "money": "USD",
            "Date": "12.12.2016, 17:00",
             "asw1": 13,
            "SpecialField": 33,
            "another": 11,
            "climbedSince": 1,
            "rfeeew": 0,
            "dfffe": 10
        },
        "child2": {
            "nr": 123,
            "money": "EUR",
            "Date": "01.01.2017, 17:00",
             "asw1": 11,
            "SpecialField": 11,
            "another": 11,
            "climbedSince": 1,
            "rfeeew": 0,
            "dfffe": 10
        }
    },
    "item2": {
        "child1": {
            "nr": 552,
            "money": "USD",
            "Date": "12.4.2016, 13:00",
             "asw1": 13,
            "SpecialField": 33,
            "another": 44,
            "climbedSince": 1,
            "rfeeew": 0,
            "dfffe": 10
        },
        "child2": {
            "nr": 343,
            "money": "EUR",
            "Date": "01.01.2017, 17:00",
             "asw1": 11,
            "SpecialField": 67,
            "another": 11,
            "climbedSince": 1,
            "rfeeew": 0,
            "dfffe": 10
        }
    }

这是我的代码。

<script>
 	function getApiData(tld, callback) {
	$.ajax({
		url: 'https://www.website.com/api',
		dataType: 'jsonp',
		success: function(data) {
			callback(data);
			 console.log(data);
		},
		error: function() {
			console.error('Could not get lottery jackpots!');
		}
	});
}
function drawApiData() {
	var now = new Date();
	getApiData('com', function(theStuff){
		$.each(theStuff, function( id, value ) {
			var checkStuff=[];
			if($.inArray(id, checkStuff)==-1){
				checkStuff.push(id);	
		 	$('#main2').append('Field: '+id+'<br/');
 			}
		});
	});
}
drawAllData();
 </script>

我想使用 for 循环在屏幕上打印(附加)几个值,用于对象拥有的尽可能多的项目(它不是静态的,但结构始终相同)。

我可以打印 item1、item2 但我无法访问第 2 级。

我想打印的是例如“日期”+“特殊字段”的时间。

提前感谢您的帮助! :)

【问题讨论】:

  • $.each() 方法用于 迭代 jQuery 对象 不适用于常规对象

标签: javascript jquery json object jsonp


【解决方案1】:

这就是你要找的:

var container = $("#main2");
var append = (obj) => {
  //do something with obj object
  container.append('My date: '+obj.Date);
};
for(var parent of theStuff){
  for(var child of parent){
    append(child);
  }
}

【讨论】:

  • 感谢您的帮助!我不确定我是否理解你的 for 循环。您能详细说明一下吗?
猜你喜欢
  • 1970-01-01
  • 2016-05-02
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
  • 2021-12-10
  • 2012-10-03
  • 2020-01-02
  • 2016-01-10
相关资源
最近更新 更多