I'm trying to add data to an array, and getting a weird result.
var arr = [];
var obj1 = { data: ["a","b"]};
var obj2 = { data: ["c","d"]};
arr.push(obj1);
arr[0].data.push(obj2.data);
console.log(arr[0].data);
// 1) what i want: [ ["a", "b"], ["c", "d"] ]
// 2) what i get: ["a", "b", ["c", "d"] ]
Any idea how can I set it up so that I get the data formatted like: [["a","b"],["c","d"]]? Here's a fiddle for it: http://jsfiddle.net/oakley808/UCQ65/
Ahmed Kotb
6,3176 gold badges36 silver badges53 bronze badges
asked May 15, 2013 at 0:02
-
3Why are you creating objects if you only want arrays?James Montagne– James Montagne2013年05月15日 00:04:23 +00:00Commented May 15, 2013 at 0:04
-
^^What he said. Also, that's not a 'weird' result at all - you're inserting an array as an element into another array.Iskar Jarak– Iskar Jarak2013年05月15日 00:05:10 +00:00Commented May 15, 2013 at 0:05
-
This is a simplified example. The objects actually are more complex.Michael Oakley– Michael Oakley2013年05月15日 00:14:07 +00:00Commented May 15, 2013 at 0:14
-
Yes, but you don't need the objects to demonstrate what you are trying to do with the arrays.Iskar Jarak– Iskar Jarak2013年05月15日 00:19:06 +00:00Commented May 15, 2013 at 0:19
-
You're right. Let me try and clarify. What I actually need to do is add object1 to the array, then essentially merge object2 into object1. The data arrays within the objects are x,y coordinates, which is why i need them paired up.Michael Oakley– Michael Oakley2013年05月15日 00:38:18 +00:00Commented May 15, 2013 at 0:38
1 Answer 1
Try this:
var arr = [];
var obj1 = { data: ["a","b"]};
var obj2 = { data: ["c","d"]};
arr.push(obj1.data);
arr.push(obj2.data);
console.log(arr);
enter image description here
answered May 15, 2013 at 0:07
3 Comments
Bruno Croys Felthes
@emrenevayeshirazi take a look at the picture, i have a array with 2 other arrays with 2 elements
Michael Oakley
You're right @BrunoCroysFelthes . But sadly the array 'arr' needs to contain objects. arr[{data[[x1,y1],[x2,y2]]},...{},...{data[[x8,y8],[x9,y9]]}]. I think I oversimplified too much in my original post.
Bruno Croys Felthes
@MichaelOakley Do a better feddle, or post your original variable structure, then we can help you better.
lang-js