Skip to content Skip to sidebar Skip to footer

Create JSON Structure From JSON Results

Given this JavaScript object: [ { 'label': 'NewNetworkServiceProvider', 'value': 'NewNetworkServiceProvidered46c4ee-7ec1-45d6-9d13-94e301d2f890' }, { 'label': 'Purchase

Solution 1:

You can use a simple iteration over the array

var obj = {
    header: {}
};
lscheader.data.results.forEach(function (item) {
    obj.header[item.label] = item.value;
});
lscResp.data.results.push(obj);

Demo: Fiddle


To make your code

//need to use the same object in the iteration, should not recreate it in the loop
var obj = {
    header: {}
};
//array index is from 0..length-1
for (var i = 0; i < lscheader.data.results.length; i++) {
    if (lscheader.data.results[i] != undefined) {
        var sLabel = lscheader.data.results[i].label;
        var sValue = lscheader.data.results[i].value;

        //use bracket notation
        obj[sLabel] = sLabel;
    }
}
lscResp.data.results.push(obj);
console.log(obj)

Since you need to have the object key from the value of a variable, you need to use the bracket notation


Solution 2:

How about mapping the array onto an object?

var obj = {Header: {}};
var header = obj.Header;
lscheader.data.results.map(function (item) {
    header[item.label] = item.value;
});

obj should now hold the structure you want.


Post a Comment for "Create JSON Structure From JSON Results"