0

The Problem is the following: I have a JSON file that has objects with the following name: "item0": { ... }, "item1": { ... }, "item2": { ... }. But I can't access them when going through an if method.

What I've done so far:

$.getJSON('/assets/storage/items.json', function(data) {
    jsonStringify = JSON.stringify(data);
    jsonFile = JSON.parse(jsonStringify);

    addItems();
});

var addItems = function() {
    /* var declarations */

    for (var i = 0; i < Object.keys(jsonFile).length; i++) {
        path = 'jsonFile.item' + i;
        name = path.name;
        console.log(path.name);
        console.log(path.type);
    }

}

If I console.log path.name it returns undefined. But if I enter jsonFile.item0.name it returns the value. So how can I use the string path so that it's treated like an object, or is there an other way on how to name the json items.

W. George
  • 9
  • 1

3 Answers3

1

As others stated 'jsonFile.item' + i is not retrieving anything from jsonFile: it is just a string.

Other issues:

  • It makes no sense to first stringify the data and then parse it again. That is moving back and forth to end up where you already were: data is the object you want to work with
  • Don't name your data jsonFile. It is an object, not JSON. JSON is text. But because of the above remark, you don't need this variable
  • Declare your variables with var, let or const, and avoid global variables.
  • Use the promise-like syntax ($.getJSON( ).then)
  • Iterate object properties without assuming they are called item0, item1,...

Suggested code:

$.getJSON('/assets/storage/items.json').then(function(data) {
    for (const path in data) {
        console.log(data[path].name, data[path].type);
    }
});
trincot
  • 317,000
  • 35
  • 244
  • 286
0

What you want is to use object notation using a dynamic string value as a key instead of an object key. So, instead of using something like object.dynamicName you either have use object[dynamicName].

So in your example it would be like this.

path = 'item' + i;
jsonFile[path].name
Aer0
  • 3,792
  • 17
  • 33
0

I'm afraid you cannot expect a string to behave like an object.

What you can do is this:

path = `item${i}`
name = jsonFile[path].name
SerShubham
  • 873
  • 4
  • 10