您好谁可以帮我这个?我有一个json,我解析它,之后我需要创建一个数组
这是我的json:
imageView.layer.contentsRect = CGRectInset(imageView.bounds, 4, 4)
我有一个功能
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 :(得分:1)
您提供的JSON无效。我假设您不能使用数组,但您可以从Array.prototype借用方法来帮助格式化数据。
我已在<!-- Layout A -->
<div class="row">
<div class="col-lg-8 col-md-8 col-sm-8 text-center">
<div class="image">
Image
</div>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 text-center">
<div class="text">
Text Content
</div>
</div>
</div>
<!-- Layout B -->
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-4 text-center">
<div class="text">
Text Content
</div>
</div>
<div class="col-lg-8 col-md-8 col-sm-8 text-center">
<div class="image">
Image
</div>
</div>
</div>
功能中自动设置长度(如果尚未设置)。
它的一个问题是它将返回一个实际数组,而不是像对象那样的数组。如果你需要一个像对象一样的数组,你可以将数组减少到一个对象。
请参阅内联评论了解更多信息。
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 ) ) );
答案 1 :(得分:0)
使用.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);