Brian J Brian J - 26 days ago 10
JSON Question

How to split a JSON property value adding sub property names?

I'm retrieving an array of JSON objects and then using JS split the contents of a property into a sub-array for parsing requirements.

But I'm not sure how to add a sub property name to that newly created array for that property.

So now when I do a split on the property using:

for (var i = 0; i < recordsets[0].length; i++){
recordsets[0][i].Chart_Name = recordsets[0][i].Chart_Name.split(',');
}


I get the following output:

"Chart_Name":[
"Criticality",
" Status"
],


But I'm aiming to add a property name to each array value like:

"Chart_Name":[
{name: "Criticality"},
{name: "Status"}
],


Question:

How can I split Json string into sub property array?

This is a gist of the JSON array for context:

[
[
{
"Dashboard_Name":"my dashboard",
"Chart_Name":[
"Criticality",
" Status"
]
}
]
]

Answer

You could use Array#map and return an object.

for (var i = 0; i < recordsets[0].length; i++){ 
    recordsets[0][i].Chart_Name = recordsets[0][i].Chart_Name.split(',').map(function (a) { 
        return { name: a };
    });
}

Or rewrite the whole a bit shorter

recordsets[0].forEach(function (a) { 
    a.Chart_Name = a.Chart_Name.split(',').map(function (b) { 
        return { name: b };
    });
});

Post edit suggestion without split

for (var i = 0; i < recordsets[0].length; i++){ 
    recordsets[0][i].Chart_Name = recordsets[0][i].Chart_Name.map(function (a) { 
        return { name: a };
    });
}

Or rewrite the whole a bit shorter

recordsets[0].forEach(function (a) { 
    a.Chart_Name = a.Chart_Name.map(function (b) { 
        return { name: b };
    });
});