Arrays stored in data storage

csp-unit-5

#1

I know that I can store an array in code.org’s data storage, but can readRecords pull an array out of a column?


#2

If you want to record and retrieve arrays in the data backend you’ll need to encode it as JSON. So when recording, use JSON.stringify(my_array) and then when retrieving you can decode that JSON string with JSON.parse(my_array). Here’s a quick example that that stores an array to a key/value pair and then immediately retrieves it https://studio.code.org/projects/applab/3uEp0OBgJkzqRYdfrK5Dag/view


#3

Thank you, that was a perfect solution.
The same process can for more complicated objects as well.
var assn1 = new ASSIGNMENT(“Work”, {“val”:80,“weight”:0.2});
var assnCopy;
function ASSIGNMENT (name, grade){
this.name = name;
this.grade = grade;
}

createRecord("mytable", {data:JSON.stringify(assn1)}, function() {});
readRecords("mytable", {}, function(records) {
  console.log(records[2].data.name);//undefined
  console.log(records[2].data); //{"name":"Work","grade":{"val":80,"weight":0.2}}
  assnCopy = JSON.parse(records[2].data);
  console.log(assnCopy);//{"name":"Work","grade":{"val":80,"weight":0.2}}
  console.log(assnCopy.grade.val);//80
});

Reading Objects from readRecords