这是我的代码:
var pictures = {};
for (var key in pics) {
//just interested in the first 3 profile pictures.
if (i < 3){
var view = Titanium.UI.createImageView({
image: pics[key].source,
width: 'auto',
height: 'auto'
});
$.scrollableView.addView(view);
//store in json object
pictures['source'] = '[' + pics[key].source + ']';
i++;
} else {
//break out of loop
break;
}
}
好的,我知道在JSON中创建一个JSON数组的语法基本上是这样的:
[ { something, something 2, something 3 }],
如何根据上面的代码动态创建一个json数组。
pictures['source'] = '[' + pics[key].source + ']';
这只会将最后pics[key].source
存储在列表中。
答案 0 :(得分:1)
这是你需要的吗?
var pics = [{ source: 'foo' }, { source: 'bar' },
{ source: 'foo' }, { source: 'bar' }];
var pictures = pics.slice(0, 3).map(function(pic, i){
var ret = {};
ret[i] = pic.source;
return ret;
});
console.log(JSON.stringify(pictures)); // [{"0":"foo"},{"1":"bar"},{"2":"foo"}]
根据评论更新:
var pics = [{ source: 'foo' }, { source: 'bar' },
{ source: 'foo' }, { source: 'bar' }];
var imgSources = pics.slice(0, 3).map(function(pic, i){
return pic.source;
});
console.log({ images: imgSources }); // {"images":["foo","bar","foo"]}
答案 1 :(得分:0)
这样的事情:
var pictures = [];
// your code..........
pictures.push(pics[key].source);
//more code....
var jsonStr = JSON.stringify(pictures);