1

I have an two element array looking like this

headers = [{x: 1, y: 2},{x: 2, y: 3}]

I have another three element array that looks like:

ans = [{r: true},{r: false},{r:true}]

How can I add the second array to the first row of the first array to give:

[{x: 1, y: 2, ans: [{r: true},{r: false},{r:true}] },{x: 2, y: 3}]

Note that I don't want to define ans beforehand as it could be an array or something else. Also sorry but I think my representation of the array might not be quite the correct syntax. Hope it makes sense.

1
  • "Cannot set property 'ans' of undefined" is different than "ans is undefined". Which one of these errors is raised? Commented Nov 14, 2013 at 14:16

4 Answers 4

7

You actually want to add another property to an element in an array. You can do it like this

 headers[0].ans = ans;
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry for the repeated same comment but headers[0] is an object with fields. When I try the above it says "ans is undefined".
2

You could do something like this...

var headers = [{x: 1, y: 2},{x: 2, y: 3}];
var ans = [{r: true},{r: false},{r:true}];

// define what you want the newly added property to be called
var collectionName = "ans";

// assign it only to the first item in the headers array
headers[0][collectionName] = ans;

// here are your results
console.log(JSON.stringify(headers));

here is a working fiddle that will output the array for you to look at in an output div

http://jsfiddle.net/9KR2P/

4 Comments

This still gave me: Cannot set property 'ans' of undefined
@SamanthaJ take a look at the working fiddle link which I've added in an edit.
Thanks. I will look at this now. I am having some trouble getting internet now. Did you see the other answer and fiddle. It's different from yours. Just wonder which is best. Right now I cannot get fiddle to come up but hopefully soon.
its different because its using dot notation to reference the property, which is good - my example uses [] to reference the property so that we can change the property name of "ans" in the target object to whatever you want it to be. I just put in more code to illustrate that really.
2

Simply assign your property to your object : headers[0].ans = ans

1 Comment

I tried this but headers[0] is an object with fields. When I try the above it says "ans is undefined".
0
var headers = [{x: 1, y: 2},{x: 2, y: 3}],
    ans = [{r: true},{r: false},{r:true}];

headers[0].ans = ans;

1 Comment

Jon - I tried this but headers[0] is an object with fields. When I try the above it says "ans is undefined".

Your Answer

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.