[英]How to populate a json array object dynamically?
here is my code: 这是我的代码:
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;
}
}
Ok I know in JSON to create a JSON Array the syntax is basically this: 好的,我知道在JSON中创建JSON数组的语法基本上是这样的:
[ { something, something 2, something 3 }],
how can I create an json array dynamically based on the code above. 如何根据上面的代码动态创建json数组。
pictures['source'] = '[' + pics[key].source + ']';
This only stores the last pics[key].source
in the list. 这只会在列表中存储最后的
pics[key].source
。
Is this what you need? 这是您需要的吗?
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"}]
Update based on comment: 根据评论更新:
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"]}
Something like this: 像这样:
var pictures = [];
// your code..........
pictures.push(pics[key].source);
//more code....
var jsonStr = JSON.stringify(pictures);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.