1

I am trying to create a JSON array inside another JSON array.
I think I did it right, but when I call the second array it returns undefined.

JSON file :

var files = [
    {"Files" : [
        {"file1" : "file1"},
        {"file2" : "file2"},
        {"file3" : "file3"}
    ]},

    {"Texts" : [
        {"file4" : "file4"},
        {"file5" : "file5"},
        {"file6" : "file6"}
    ]}
];

When I trying this command it works -

console.log(files[0]); // Works, returns the array

But when I trying this command it not working -

console.log(files[0][1]); // Not working, return undefined

I expect that this will return file2.

What I did wrong ?

EDIT : The script gets JSON file like that from the server, and the script need to loop through the JSON. So think about the names ( Files, Texts, file1, file2 etc.. ) as unknown..

3 Answers 3

5
console.log(files[0]["Files"])  // will return array with file 1-3
console.log(files[0]["Texts"])  // will return array with file 4-6   

or

console.log(files[0].Files)  // will return array with file 1-3
console.log(files[0].Texts)  // will return array with file 4-6

in you example files[0][1] work for json like this

var files = [
    [
        {"file1" : "file1"},
        {"file2" : "file2"},
        {"file3" : "file3"}
    ],
    [
        {"file4" : "file4"},
        {"file5" : "file5"},
        {"file6" : "file6"}
    ]
];  

EDIT
in this case you can use next for-loop

for (var key in files[0])
{
   files[0][key] // here key is "Files", this will return files 1-3       
}​
Sign up to request clarification or add additional context in comments.

1 Comment

The script gets JSON file like that from the server, and the script need to loop through the JSON. So think about the names as unknown..
5

This:

console.log(files[0]);

does not log an array, it's the object that's the first element of the array. To get to the inner array, you have to get at the "Files" attribute of that object:

console.log(files[0].Files[1]);

What that will log is not just the string "file2", but the entire object, { file2: "file2" }. In JavaScript, object properties with string property names cannot be accessed by numeric index. That is, in the object:

{ "foo": "hello world" }

there simply is no [0] property. Arrays in JavaScript are also objects and can have string-named properties, but they're separate from the collection of numerically-indexed properties.

Comments

2

The arrays are inside of the Files property:

console.log(files[0].Files[0]);
console.log(files[0].Files[1]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.