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.

3
  • 6
    Don't try to generate a JSON string manually. Create a Javascript object and use JSON.stringify() Commented Apr 19, 2014 at 22:34
  • so basically create an array and then use json.stringify? Commented Apr 19, 2014 at 22:36
  • Well, yea. Right now you're overwriting your "source" property on your pictures object, hence only getting the last value. Commented Apr 19, 2014 at 22:40

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

basically that { images: [img 1, img2, img3 ]}
0

Something like this:

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


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

//more code....


var jsonStr = JSON.stringify(pictures);

JSON.stringify

3 Comments

thanks that works, how can i create a multidimensional array, so that the json string has a key?
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.
so its like { images: [img 1, img2, img3 ]}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.