0

I am taking a json file and reorganizing it as a object in a new format (Not the same formatting as the json file I am reading, as I want to group variables differently) so I can use it. This requires creating a lot of variables with names that are unknown in advance.

I can dynamically create a new variable in my project like this:

object[variablename]

However, I would like to be able to do things like this

library[musicLibrary.Key].name = musicLibrary.alblum;

and

library[musicLibrary.Key].songs.[musicLibrary.title].name = musicLibrary.song;

Is there any way I can possibly do this?

My current looping code for the json looks like this:

var library = {}; 

for(var i = 0; i < musicList.songs.length; i++) {
//read json and reorganise it into a object
}
6
  • you can try use JSON.parse with reviver function what json you try parse? Commented Feb 7, 2014 at 5:08
  • library[musicLibrary.Key].name should be valid syntax...maybe you just need to add library[musicLibrary.Key]={} first? Commented Feb 7, 2014 at 5:11
  • JSON are you Arrays by Key stackoverflow.com/questions/684672/… Commented Feb 7, 2014 at 5:13
  • @Grundy I have seen that but it won't work for me becuase I am changing up the json file when I convert it into a object, It's not quite the same as the original json file. Commented Feb 7, 2014 at 5:14
  • @Passerby Thanks! That worked. And advice for my second piece? Commented Feb 7, 2014 at 5:16

1 Answer 1

1
for(var i = 0; i < musicList.songs.length; i++) {
    var key = musicLibrary.Key;
    library[key] = library[key] || {};
    library[key]['name'] = musicLibrary.alblum;
    library[key]['songs'] = library[key]['songs'] || {};
    library[key]['songs'][musicLibrary.title] = library[key]['songs'][musicLibrary.title]  || {};
    library[key]['songs'][musicLibrary.title]['name'] = musicLibrary.song;
}
Sign up to request clarification or add additional context in comments.

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.