Reputation: 3794
Using this to load the json
var jsonParsed = JSON.parse(localStorage.getItem('test'));
Using this to save
var jsonData = ko.toJSON(viewModel);
Now when readying it in i know i can get my values like sooo...
jsonParsed.AOfficer
(if A officer was a feild with a value) I know that the above code would return the value of the json feild AOfficer but how do i get it to return the name of all the feilds in a json e.g returning that it holds Aofficer rather than its value.
Im wanting to know this because im dynamicly creating forms using the json feild name for the form id and value for form value.
Thanks
Upvotes: 0
Views: 207
Reputation: 1368
Assuming that jsonParsed is something like:
var field = {
"field1": "Test data",
"field2": "Test data"
};
You could do:
for(var field in fields){
if(fields.hasOwnProperty(field)){
console.log(field, fields[field]);
}
};
That iterates trough all the top-level object props and returns its name, and value.
Upvotes: 2
Reputation: 22421
Use for in
loop with optional .hasOwnProperty
check to loop over object's properties.
Upvotes: 1