VinsMat
VinsMat

Reputation: 15

Converting a comma separated list of json objects to an array

I have a problem with a received javascript object. I receive something like this:

{
 "name":"a",
 "surname":"b"
},
{
 "name":"c",
 "surname":"d"
},
{
 "name":"e",
 "surname":"f"
}

I store it in a variable and I would like to have an array of json objects, i.e. a JSON Array .

[{ "name":"a", "surname":"b" }, { "name":"c", "surname":"d" }, { "name":"e", "surname":"f" }]

I would need something as array.push() but I can't do it if I don't split the file before.

Upvotes: 1

Views: 8335

Answers (2)

I have one function to split your Array of Objects in many Arrays as you want, see the code :)

var BATCH_SIZE = 2;

var fullList = [{name:"a",surname:"e"},{name:"a",surname:"e"}
  , {name:"a",surname:"e"},{name:"a",surname:"e"}, {name:"a",surname:"e"}];

Batchify(fullList,BATCH_SIZE);

function Batchify(fullList,BATCH_SIZE){
    var batches = [];
    var currentIndex = 0;
    while (currentIndex < fullList.length) {
       var sliceStart = currentIndex;
       var sliceEnd = currentIndex + BATCH_SIZE;
       batches.push(fullList.slice(sliceStart, sliceEnd));
       currentIndex += BATCH_SIZE;
    }
    console.log(batches);
}

I have example of code in JSfiddle, I hope solve your problem! :)

Upvotes: 0

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34199

This is an invalid notation - either JavaScript object or JSON. If you can fix your input or can make someone fix it, then it is definitely better to make your data source be valid.

However, sometimes we have to work with wrong data (external providers etc.), then you can make it a valid JSON array by adding a couple brackets in the beginning and the end:

var str = '{ "name":"a",  "surname":"b" }, {  "name":"c",  "surname":"d" }, {  "name":"e",  "surname":"f" }';
var arr = JSON.parse("[" + str + "]");
//console.log(arr);

for (var i = 0; i < arr.length; i++)
{
  console.log("Name #" + (i + 1) + ": " + arr[i].name);
  console.log("Surname #" + (i + 1) + ": " + arr[i].surname);
}

It can look a little bit hacky, but it is the best thing you can do when you have to work with such input.
It looks much better than trying to split an object by commas manually, at least for me.

Upvotes: 4

Related Questions