How to create dynamic array for pairs of data using javascript?

104 views Asked by At

How to create dynamic array for example pairs of data using javascript? i want the exact structure as shown in example data pairs in dynamic array. i tried code below but it seems my array is not correct. could any one help me fix it.Thanks

Note: alert(files.join('\n')); shows [object object] Example of pairs of data to be stored in array

files: [

        {'url': 'http://www.somesite.com/1.jpg', 'filename': 'new1.jpg'},
        {'url': 'http://www.somesite.com/2.jpg', 'filename': 'new2.jpg'},
        {'url': 'http://www.somesite.com/2.jpg', 'filename': 'new3.jpg'},
    ],

My array creation function:

<script>
var i=1;
  files = new Array();   
    function addtoArray(a,b){
    alert("URL:"+a+"\nFileName:"+b);

    files[i] = { url: +a, filename: +b };
    i++;
    alert(files.join('\n'));
    };
</script>
<body>
<button onclick="addtoArray('http://www.somesite.com/1.jpg','new1.jpg')">add to array</button>

<button onclick="addtoArray('http://www.somesite.com/2.jpg','new2.jpg')">add to array</button>
2

There are 2 answers

2
aadarshsg On BEST ANSWER

Try this.

function addtoArray(a,b){
files.push({ url: a, filename: b });
};

EDIT: Adding code to display the content

alert(JSON.stringify(files));
1
DLH On

This seems to be working in a Codepen. (http://codepen.io/dharshba/pen/YXQvPP)

<script>
files = [];

function addtoArray(a, b) {
  var obj = {
    url: a,
    filename: b
  };
  files.push(obj);
};
</script>

I believe the +a and +b were at least part of the issue. Using the + operator that way attempts to coerce the strings into numbers, which wasn't really what you wanted.

To answer your question about seeing the array in a human-readable form in an alert, you can use:

alert(JSON.stringify(files));