2

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"
         ]
      }  
   ]
]
Community
  • 1
  • 1
Brian Var
  • 6,029
  • 25
  • 114
  • 212

1 Answers1

1

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 };
    });
});
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I'm a bit curious: why do you use the split method instead of a straightforward `a.Chart_Name = a.Chart_Name.map(function(b) {return {"name": b};});` – Eineki Nov 11 '16 at 11:42
  • @Eineki, i suppose `a.Chart_Name` is a string with comma sparators. – Nina Scholz Nov 11 '16 at 11:48
  • @NinaSchloz Ah, Ok. It appears to be an array, from the example. I noticed just now your answer was written earlier than the question edit with a sample of the structure. – Eineki Nov 11 '16 at 12:22