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.
-
"Cannot set property 'ans' of undefined" is different than "ans is undefined". Which one of these errors is raised?user1636522– user16365222013年11月14日 14:16:28 +00:00Commented Nov 14, 2013 at 14:16
4 Answers 4
You actually want to add another property to an element in an array. You can do it like this
headers[0].ans = ans;
1 Comment
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
4 Comments
Simply assign your property to your object : headers[0].ans = ans
1 Comment
var headers = [{x: 1, y: 2},{x: 2, y: 3}],
ans = [{r: true},{r: false},{r:true}];
headers[0].ans = ans;