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,9588 gold badges43 silver badges64 bronze badges
asked Nov 20, 2015 at 13:32
Gerrie van Wyk
6972 gold badges8 silver badges30 bronze badges
3 Answers 3
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(',') : [];
})
answered Nov 20, 2015 at 13:37
jeremija
2,5581 gold badge21 silver badges28 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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;
}
});
answered Nov 20, 2015 at 13:38
epascarello
208k20 gold badges206 silver badges246 bronze badges
Comments
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>
answered Nov 20, 2015 at 13:42
Zohaib Ijaz
23k7 gold badges43 silver badges63 bronze badges
1 Comment
Gerrie van Wyk
Thanks this is a great answer since it tests the "aaa, bbb" csv issue for all keys.
lang-js
"Users": ["USRA"].