0

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:

[ { something, something 2, something 3 }],

how can I create an json array dynamically based on the code above.

pictures['source'] = '[' + pics[key].source + ']';

This only stores the last pics[key].source in the list.

Nope
  • 22,147
  • 7
  • 47
  • 72
bobo2000
  • 1,779
  • 7
  • 31
  • 54
  • 6
    Don't try to generate a JSON string manually. Create a Javascript object and use `JSON.stringify()` – Johan Apr 19 '14 at 22:34
  • so basically create an array and then use json.stringify? – bobo2000 Apr 19 '14 at 22:36
  • Well, yea. Right now you're overwriting your "source" property on your `pictures` object, hence only getting the last value. – Johan Apr 19 '14 at 22:40

2 Answers2

2

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

http://jsfiddle.net/psMSY/

Johan
  • 35,120
  • 54
  • 178
  • 293
0

Something like this:

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


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

//more code....


var jsonStr = JSON.stringify(pictures);

JSON.stringify

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
  • thanks that works, how can i create a multidimensional array, so that the json string has a key? – bobo2000 Apr 19 '14 at 22:44
  • Are you talking about a dictionary? what do you need under pictures? if you are talking about a complex object then: var pictures = []; pictures.push({name:'pic1.jpg',date:'12-10-2013',takenBy:'david'}); now pictures[0] is a complex object. – Amir Popovich Apr 19 '14 at 22:47
  • so its like { images: [img 1, img2, img3 ]} – bobo2000 Apr 19 '14 at 22:52