你好,谁能帮我?我有一个json并解析它,之后我需要为每个项目创建一个数组
这是我的json:
0: Object
title: "title0"
content: "content0"
comment: "comment0"
1: Object
title: "title1"
content: "content1"
comment: "comment1"
我有一个功能
var mystockinfo = [];
function uploadSomething(data){
var myjsonparse = JSON.parse(data.div);
for (var i = 0; i < myjsonparse.length;){
mystockinfo[i][0] = myjsonparse[i].title;
mystockinfo[i][1] = myjsonparse[i].content;
mystockinfo[i][2] = myjsonparse[i].comment;
i++;
}
}
console.log(mystockinfo);
我需要
[ 0 => [title0, content0, comment0], 1 => [title1, content1, comment1]]
你能帮我做这个吗???
您提供的JSON无效。我假设您不能使用数组,但可以借用array.prototype中的方法来帮助格式化数据。
如果尚未设置,我已在reduceToValues
函数中自动设置长度。
它的一个问题是,它将返回一个实际的数组,而不是类似数组的对象。如果在另一端需要一个类似数组的对象,可以将数组简化为一个对象。
有关详细信息,请参阅内联注释。
var data = {
0: {
title: "title0",
content: "content0",
comment: "comment0"
},
1: {
title: "title1",
content: "content1",
comment: "comment1"
}
}
function reduceToValues( data ){
// if you add a length property to the object it will be array like
// then you can use the native array methods with it.
data.length = data.length || Object.keys(data).length;
// map the array like object to a single array
return Array.prototype.map.call( data, function( item ){
var values = [];
// loop through the object and save the values
for( var key in item ){
values.push( item[key] );
}
// return the values
return values;
}, []);
}
function arrayToArrayLikeObject( arr ){
return arr.reduce(function( ret, item, ii ){
ret[ ii ] = item;
return ret;
}, {});
}
console.log( reduceToValues( data ) );
// if you need an array like object out the other end
console.log( arrayToArrayLikeObject( reduceToValues( data ) ) );
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
使用.map()
是一种简单的方法,可以循环遍历数组并将其转换为所需的嵌套数组。
var obj = [{
title: "title0",
content: "content0",
comment: "comment0"
}, {
title: "title1",
content: "content1",
comment: "comment1"
}];
var updated = obj.map(function(ind) {
return [ind.title, ind.content, ind.comment];
});
console.log(updated);