JS / Vue:如果一个字段相同,则合并两个数组

时间:2020-10-27 18:22:41

标签: javascript vue.js

我似乎无法管理通过将每个“ id”公共字段“分组”来将两个数组合并为一个数组的正确方法。

以下是我最后一次尝试:

// editedItem.extra_tools ///

0:
{
    extra_tool_password: "vpn pwd"
    extra_tool_username: "vpn us"
    id_extra_tool: "8"
},
1:
{
    extra_tool_password: ""
    extra_tool_username: "off"
    id_extra_tool: "1"
},
2:
{
    extra_tool_password: ""
    extra_tool_username: "HS"
    id_extra_tool: "7"
}

应通过id_extra_tool合并到:

// this.extras //
0:
{
extra_params: 1
extra_tool_name: "Hubspot"
extra_tool_password: "password_new"
extra_tool_username: null
id_extra_tool: (1)
}
1:
{
extra_params: 1
extra_tool_name: "Office"
extra_tool_password: "12345"
extra_tool_username: "user_office"
id_extra_tool: (7)
}
{
2:
extra_params: 0
extra_tool_name: (...)
extra_tool_password: (...)
extra_tool_username: (...)
id_extra_tool: (8)
        this.extrasEdited = []
        for (i = this.extras.length - 1; i >= 0; i--) {
          this.extrasEdited.push({
            id_extra_tool: this.editedItem.extra_tools[i].id_extra_tool,
            extra_tool_username: this.editedItem.extra_tools[i].extra_tool_username,
            extra_tool_password: this.editedItem.extra_tools[i].extra_tool_password
          })
          this.editedItem.extra_tools.forEach((element, index) => {
            console.log(element.id_extra_tool, this.extrasEdited[index].id_extra_tool)
            if (element.id_extra_tool === this.extrasEdited[index].id_extra_tool) {
              this.extrasEdited.push({
                extra_params: element.extra_params,
                extra_tool_name: element.extra_tool_name
              })
            }
          })
        }

我想要:

// this.extras //
0:
{
extra_params: 1
extra_tool_name: "Hubspot"
extra_tool_password: "password_new"
extra_tool_username: null
id_extra_tool: 1
}
1:
{
extra_params: 1
extra_tool_name: "Office"
extra_tool_password: "12345"
extra_tool_username: "user_office"
id_extra_tool: 7
}
{
2:
extra_tool_password: "VPN"
extra_tool_username: "HS"
id_extra_tool: "8"
extra_tool_password: "user_VON_pswwww"
extra_tool_username: "user_VPN"

现在应该更清楚了...

ty!

1 个答案:

答案 0 :(得分:0)

您可以尝试:

var mergedArray =[]
 extra_tools.map(x => {
      extras.map(y => {
        if (x.id_extra_tool === y.id_extra_tool) {
          mergedArray.push(Object.assign(x, y));
        }
      })
    })