将javascript数组插入另一个数组

时间:2014-03-06 00:06:13

标签: javascript arrays

考虑以下两个数组。如何将数组“行”附加到数组“array1”。我试过.push但是它附加在数组之外。我也试过.unshift,它没有给我想要的结果。

array1 = [
  {
    "Activity #": "1111111",
    "Customer": "Last, First",
    "Tenure": "0 Year 2 Months",
    "Account #": "0000000"
  }];

lines = [
  {
    "Line #": "1",
    "Action Required": "New",
    "Status": "Closed",
    "Product Line": "test line1",
    "Product": "product1"
  },
  {
    "Line #": "2",
    "Action Required": "New",
    "Status": "Closed",
    "Product Line": "test line2",
    "Product": "product2"
  }];

我想要这样的事情。

my_array = [
{
    "Activity #": "1111111",
    "Customer": "Last, First",
    "Tenure": "0 Year 2 Months",
    "Account #": "0000000",
    "lines": [{
            "Line #": "1",
            "fields": "keys"
        },
        {
            "Line #": "2",
            "fields": "keys"
        }]
}] 

使用上面提到的方法,我会得到类似的东西。

my_array = [
{
    "Activity #": "1111111",
    "Customer": "Last, First",
    "Tenure": "0 Year 2 Months",
    "Account #": "0000000"
}, [
    {
        "Line #": "1",
        "fields": "keys"
    }, {
        "Line #": "2",
        "fields": "keys"
    }]
];

希望有人能提供帮助,我的问题很清楚。

1 个答案:

答案 0 :(得分:5)

看起来你想将lines作为属性添加到数组中的对象,所以你必须这样做:

array1[0].lines = lines;

如果你在array1中有更多元素,你还没有解释究竟应该发生什么,所以我不能就此发表任何意见。