如何将Javascript中的2个数组与标题组合在一起

时间:2017-05-10 04:25:40

标签: javascript arrays

所以我有2个数组: (来自用户表)

[{
  "id": "123",
  "name": "Peter",
  "description": "person in the office"
}]

(来自部门表)

[{
  "id": "R1",
  "name": "Marketing",
  "description": "Yea Marketing"
},
{
  "id": "R2",
  "name": "Sales",
  "description": "More Sales"
}]

我想要做的是将两个数组合并为一个数组,如下所示:

[{
  "user": [{
      "id": "123",
      "name": "Peter",
      "description": "person in the office" }],
  "department": [{
      "id": "R1",
      "name": "Marketing",
      "description": "Yea Marketing"
    },
    {
      "id": "R2",
      "name": "Sales",
      "description": "More Sales"
    }]
}]

我知道如何连接数组和推送,但两种方式只合并数据,而不允许我添加用户和部门的标题。如果我使用带有字符串的concat添加到标题中,那么我会回来[{" \" user \":[{\ n \" name \" :. ....

有没有办法可以组合数组并添加某种类型的标题字段?

2 个答案:

答案 0 :(得分:2)

这就是你要追求的吗?

var user = [{
  "id": "123",
  "name": "Peter",
  "description": "person in the office"
}];

var departments = [{
  "id": "R1",
  "name": "Marketing",
  "description": "Yea Marketing"
},
{
  "id": "R2",
  "name": "Sales",
  "description": "More Sales"
}];

var combined = [{
    user: user,
    department: departments,
}];

答案 1 :(得分:1)

.notice