简体   繁体   中英

How can I add an array into another array in Javascript?

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.

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

 headers[0].ans = ans;

只需将属性分配给对象: headers[0].ans = ans

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/

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

headers[0].ans = ans;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM