0

I have the following JSON data:

[
    {
        "Title": "PAGE A",
        "Users": "USRA"
    },
    {
        "Title": "PAGE B",
        "Users": "USRA,USRB"
    }
]

What would be the best way to convert the fields with "," in to arrays? and get using javascript:

[
    {
        "Title": "PAGE A",
        "Users": "USRA"
    },
    {
        "Title": "PAGE B",
        "Users": ["USRA","USRB"]
    }
]
Karl Gjertsen
  • 4,690
  • 8
  • 41
  • 64
Gerrie van Wyk
  • 679
  • 8
  • 27

3 Answers3

2

You could do:

data = [
    {
        "Title": "PAGE A",
        "Users": "USRA"
    },
    {
        "Title": "PAGE B",
        "Users": "USRA,USRB"
    }
]

data.forEach(function(item) {
    // the if clause keeps the single user outside of an array
    if (item.Users && item.Users.indexOf(',') >= 0) {
        item.Users = item.Users.split(',');
    }
})

In case you wish to keep a consistent data type (make the Users property always be an Array):

data.forEach(function(item) {
    item.Users = item.Users ? item.Users.split(',') : [];
})
jeremija
  • 2,338
  • 1
  • 20
  • 28
1

A simple for each with a split is all you need

var data = [
    {
        "Title": "PAGE A",
        "Users": "USRA"
    },
    {
        "Title": "PAGE B",
        "Users": "USRA,USRB"
    }
];

data.forEach( function (obj) {
    obj.Users = obj.Users.split(",");
});

Now if you really do not want that one to be an array, than you need to add an if check.

data.forEach( function (obj) {
    var parts = obj.Users.split(",");
    if(parts.length>1) {
        obj.Users = parts;
    }
});
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Do something like this

var input = [
        {
            "Title": "PAGE A",
            "Users": "USRA"
        },
        {
            "Title": "PAGE B",
            "Users": "USRA,USRB"
        }
    ];

var output = [];

output = input.map(function(d){
      for (key in d){
        if (d[key].indexOf(',') !== -1){
          d[key] = d[key].split(',');
          }
      } 
     return d;

});

$('#result').html(JSON.stringify(output));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60