如何动态填充json数组对象?

时间:2014-04-19 22:30:59

标签: javascript arrays json

这是我的代码:

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存储在列表中。

2 个答案:

答案 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"]} 

http://jsfiddle.net/psMSY/

答案 1 :(得分:0)

这样的事情:

var pictures = [];
// your code..........


pictures.push(pics[key].source);

//more code....


var jsonStr = JSON.stringify(pictures);

JSON.stringify