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"]
    }
]
3
  • Take a look here Commented Nov 20, 2015 at 13:34
  • 1
    You would need to make the first Users be "Users": ["USRA"]. Commented Nov 20, 2015 at 13:35
  • Why on earth would you want an inconsistent data type? Make them all arrays, don't matter if they only have 1 element or not Commented Nov 20, 2015 at 13:39

3 Answers 3

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(',') : [];
})
Sign up to request clarification or add additional context in comments.

Comments

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;
    }
});

Comments

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>

1 Comment

Thanks this is a great answer since it tests the "aaa, bbb" csv issue for all keys.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.