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
}
joshua-anderson
  • 4,458
  • 5
  • 35
  • 56
  • you can try use [JSON.parse with reviver function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) what json you try parse? – Grundy Feb 07 '14 at 05:08
  • `library[musicLibrary.Key].name` should be valid syntax...maybe you just need to add `library[musicLibrary.Key]={}` first? – Passerby Feb 07 '14 at 05:11
  • JSON are you Arrays by Key http://stackoverflow.com/questions/684672/loop-through-javascript-object – CubanAzcuy Feb 07 '14 at 05: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. – joshua-anderson Feb 07 '14 at 05:14
  • @Passerby Thanks! That worked. And advice for my second piece? – joshua-anderson Feb 07 '14 at 05:16
  • @joshua-anderson The same: add `if(!("songs" in library[musicLibrary.Key])){library[musicLibrary.Key].songs={musicLibrary.title:{}};}` – Passerby Feb 07 '14 at 05:20

1 Answers1

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;
}
jingyinggong
  • 636
  • 5
  • 9