-2

Trying to iterate through following JSON object which i have encode in PHP, by looping through a directory containing png files. I have no luck in iterating the JSON in getLayersObject. I tried the following code and it didn't work. Any suggestions?

<?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 result

{
   "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"
    }
}
ISeeSharp
  • 53
  • 6
  • 3
    Do you have some code that you've tried? – kevin628 Nov 27 '17 at 21:39
  • Did you read the usage description of the `json` tag? – trincot Nov 27 '17 at 21:41
  • 1
    That's just an object. Not JSON. I would say that if you make phone an array instead of a nested object you'll be able to use easy array iteration without losing anything (because currently the object keys are numeric and sequential, exactly as an array is). – James Nov 27 '17 at 21:42
  • 1
    @James Actually, the keys are strings. But, your point is taken. – Scott Marcus Nov 27 '17 at 21:47
  • Im assuming the minus points are for poorly explanation. I hope the more added info and full code context gives it more clarification. – ISeeSharp Nov 27 '17 at 22:02

1 Answers1

0

This is just a regular object. Use Object.keys to enumerate it with .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]);
});
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71