[{
"name":"John"
"age":19,
"hobby":"Basketball;play computer"
},
{
"name":"Anderson"
"age":19,
"hobby":"Tennis"
}
]
约翰有2个爱好,它应该位于数组中,但我无法控制api的来源。如何使json低于格式?
[{
"name":"John"
"age":19,
"hobby":"Basketball"
},{
"name":"John"
"age":19,
"hobby":"play computer"
},
{
"name":"Anderson"
"age":19,
"hobby":"Tennis"
}
]
我是jquery新手,所以这是我尝试过的代码:
var hobbies = "";
$.each(json, function(){
hobbies = this.hobby.split(',');
});
最佳答案
var data = [{
"name": "John",
"age": 19,
"hobby": "Basketball;play computer"
}, {
"name": "Anderson",
"age": 19,
"hobby": "Tennis"
}]
$.each(data, function (index, value) {
if (value.hobby.split(';').length > 1) {
var dataArray = value.hobby.split(';');
value.hobby = dataArray[0];
dataArray.shift();
$.each(dataArray, function (innerIndex, innerValue) {
data.push({
"name": value.name,
"age": value.age,
"hobby": innerValue
});
});
}
});
console.log(data);
Fiddle Demo
关于javascript - 使用循环的javascript对象操纵,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32733239/