Search code examples
javascriptjsonangularjsionic-frameworkangular-schema-form

How to change a javascript array to a JSON object for angular-schema-form?


I need some help please converting a javascript generated array that I am preparing to be used by the angular-schema-form (requires a JSON Object).

I create an array using a for loop with some field items that I have retrieved from a $http request.

I am able to create the array without issue however, when I now try to prepare it for the angular-schema-form object this is where I am having issues converting it to the required JSON object format.

I create the array in javascript like this,

var objectSchema = [];

for(index = 0; index < instanceFields.length; index++)
{
    var fieldObject = [];

    fieldObject.id = instanceFields[index].id;
    fieldObject.title = instanceFields[index].description;
    fieldObject.type = pass_type;
    fieldObject.value = instanceFields[index].value.raw;

    objectSchema.push(fieldObject);

}

This is a console.log of the array.

console.log(objectSchema);

// result

0: Array[0]
   id: "103859"
   length: 0
   title: "Summary"
   type: "string"
   value: ""
1: Array[0]
   id: "101842"
   length: 0
   title: "Job Type"
   type: "string"
   value: "696"

I have tried to convert the above to JSON using JSON.stringify but this is returning an empty result.

I have also tried to pass the array to angula.toJson but I am getting an empty results as well.

var myJsonString = angular.toJson(objectSchema, true);
console.log(myJsonString);

// result 

[
  [],
  []
]

If you have any direction for me please to follow it would be greatly appreciated.

Thanks B


Solution

  • You are seeing this behavior because you are instantiating fieldObject as an array rather than as an object. You then try to add properties to this array, which doesn't really make sense and more importantly doesn't actually fill the data structure as you are intending.

    What then happens when you try to serialize, is that the array (which is still empty), serializes as an empty array and you lose the object properties on it.

    Try:

    var fieldObject = {};
    

    Here is a fiddle demonstrating the behavior - http://jsfiddle.net/ko8d0w5b/