【问题标题】:Trying to iterate through JSON object [duplicate]尝试遍历 JSON 对象 [重复]
【发布时间】:2018-05-11 05:46:16
【问题描述】:

尝试通过循环遍历包含 png 文件的目录来遍历我在 PHP 中编码的 JSON 对象。 我没有在 getLayersObject 中迭代 JSON 的运气。 我尝试了以下代码,但没有成功。 有什么建议?

<?php

  $dir = "layers";
  $layers = array();
    if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
       while (($file = readdir($dh)) !== false) {
        if ($file != '.' && $file != '..') {
            array_push($layers, $file);
        }
    }
    closedir($dh);
    }
}

 echo json_encode(array('phone' => $layers),  JSON_FORCE_OBJECT);
?>

JavaScript

var Layers = (function () {
var layers = [];
var mobileLayer = '';
var initialisering = function(){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var myObj = JSON.parse(xmlhttp.responseText);
            layers.push(myObj);
        }
    };
    xmlhttp.open("GET", "http://localhost/layers/get_layers.php", true);
    xmlhttp.send();
    getLayersObject();

};

var getLayersObject = function(){
    mobileLayer = document.getElementsByClassName('layer');
    Object.keys(layers.phone).forEach(function(key,index) {
        console.log(key, layers.phone[index]);
    });
}

return {
    initialisering: initialisering
    };
 })();

 window.addEventListener("load", Layers.initialisering());

JSON 结果

{
   "phone": {
    "0": "11.png",
    "1": "12.png",
    "2": "14.png",
    "3": "15.png",
    "4": "4.png",
    "5": "7.png",
    "6": "9.png",
    "7": "front_kamera.png"
    }
}

【问题讨论】:

  • 你有没有试过的代码?
  • 你看过json标签的使用说明吗?
  • 那只是一个对象。不是 JSON。我想说,如果您将 phone 设为数组而不是嵌套对象,您将能够使用简单的数组迭代而不会丢失任何内容(因为目前对象键是数字和顺序的,就像数组一样)。
  • @James 实际上,键是字符串。但是,你的观点被采纳了。
  • 我假设减分是为了解释不善。我希望更多添加的信息和完整的代码上下文能提供更多的说明。

标签: javascript json


【解决方案1】:

这只是一个普通的对象。使用Object.keys.forEach() 枚举它。

var obj = { 
 "phone": {
    "0": "11.png",
    "1": "12.png",
    "2": "14.png",
    "3": "15.png",
    "4": "4.png",
    "5": "7.png",
    "6": "9.png",
    "7": "front_kamera.png"
  }
};

Object.keys(obj.phone).forEach(function(key,index) {
    // key: the name of the object key
    // index: the ordinal position of the key within the object 
    console.log(key, obj.phone[index]);
});

【讨论】:

    猜你喜欢
    • 2013-08-25
    • 2017-07-10
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    相关资源
    最近更新 更多