1

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
5
  • 3
    Why are you creating objects if you only want arrays? Commented 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. Commented May 15, 2013 at 0:05
  • This is a simplified example. The objects actually are more complex. Commented 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. Commented 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. Commented May 15, 2013 at 0:38

1 Answer 1

6

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

@emrenevayeshirazi take a look at the picture, i have a array with 2 other arrays with 2 elements
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.
@MichaelOakley Do a better feddle, or post your original variable structure, then we can help you better.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.