【问题标题】:How to ignore/skip undefined in nested JSON javascript如何忽略/跳过嵌套 JSON javascript 中的未定义
【发布时间】:2019-06-13 13:14:57
【问题描述】:

我正在尝试从 things(1-10 个对象)和 stuff(1-10 个对象)中返回所有 it(字符串) )。我注意到我无法使用通配符来做到这一点,但我想知道是否还有其他方法可以做到这一点?

我想返回一个包含所有 it 的数组。

response.things[0].stuff[0].它会从我的第一个对象返回字符串,分别是 thingsstuff,但是

$.get("https://page.json", function(response) {
  var substr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  var arrayIts = [];
  $.each(substr , function(index, val) { 
    var arrayIts = response[index];
    console.log(arrayIts.things[index].stuff[val].it);
  });
});

Above 将返回所有 it 直到它返回 undefined 然后停止。

我如何返回所有 it 并可能忽略/跳过未定义?

到目前为止,我的解决方案如下所示。

$.getJSON('https://jsonplaceholder.typicode.com/posts', function(data) {
  	var arrayData = [];
		try {arrayData.push("<li>"+data[0].id+"</li>");}catch(e){}
		try {arrayData.push("<li>"+data[1].id+"</li>");}catch(e){}
    try {arrayData.push("<li>"+data[2].id+"</li>");}catch(e){}
 		try {arrayData.push("<li>"+data[100].id+"</li>");}catch(e){arrayData.push("<li>skipped</li>")}
    try {arrayData.push("<li>"+data[3].id+"</li>");}catch(e){}
    try {arrayData.push("<li>"+data[99].id+"</li>");}catch(e){}
		document.getElementById('listId').innerHTML = arrayData.join("");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="listId">empty</ul>

【问题讨论】:

  • response 是什么?
  • 你好,Joe,也许这会有所帮助:stackoverflow.com/questions/286141/… 你为什么不只使用一个 reduce、check/descart undefined 并将所有“it”累积到一个数组中。

标签: javascript json undefined wildcard


【解决方案1】:

只需使用 if 。

If (response[index]) arrayIts.push(response[index]);

如果 response[index]) 被定义,那么它是真的。否则是假的。

【讨论】:

  • (抱歉下面评论中的格式不正确)您好 Fero,感谢您的回答。下面是我尝试过的方法,但对我来说,当路径返回未定义时它仍然会停止。 for(var i=0; i it 未定义/不存在,它就会停止。所以它只会在未定义发生之前返回字符串。 TypeError: undefined is not an object (evalating 'arrayIts.things[index].stuff[index].it')
  • 哦,现在我明白了。您的问题是,您不仅要从单个对象中获取值,还要从嵌套对象中获取值。在那种情况下,我会去检查一下。 Test for existence of nested JavaScript object key
  • 感谢 Fero,该页面帮助我更多地了解了我的问题,但我能想到的唯一解决方案是包含在 try 中并捕获错误(不显示)并重复永远单一的价值。我的代码最终会变成数千行代码,但最终会给我想要的结果。但是你能看看我在 jsfiddle 中创建的这个例子,看看是否有其他解决方案? jsfiddle.net/3pegrzkc
  • for (i = 0; i &lt; data.length; i++) { try { arrayData.push("&lt;li&gt;"+data[ i].id+"&lt;/li&gt;"); } catch(e){ arrayData.push("&lt;li&gt;skipped&lt;/li&gt;") } }
  • 我的意思是,如果 data[i].id 存在,那么它应该推送一些东西。如果它不存在,那么它应该推送“
  • skipped
  • ”..因为,正如你所说,arrayData 在迭代后是空的,所以没有发生循环。
猜你喜欢
相关资源
最近更新 更多
热门标签