首页 > 文章列表 > Vue中如何合并两个数组并替换指定键的值?

Vue中如何合并两个数组并替换指定键的值?

483 2025-03-26

Vue中如何合并两个数组并替换指定键的值?

Vue.js中高效合并数组并替换指定键值

本文演示如何在Vue.js中合并两个数组,并同时替换目标数组中特定键的值。 假设我们有两个数组arr1arr2,需要将arr1attachment键的值替换到arr2中对应位置的attachment键。

示例数据:

let arr1 = [
    { "attachment": "https://lumall.inspures.com/images/img/product/8e358701-177a-46e1-b25e-1e13fbcd92e0.png" },
    { "attachment": "https://lumall.inspures.com/images/img/product/2adcd34a-786f-43ac-b8a8-3c45ed408019.png" }
];
let arr2 = [
    { "attachment": "blob:http://localhost:8096/9b565718-7799-440b-b761-de747f2d59c5", "number": 0, "id": "" },
    { "attachment": "blob:http://localhost:8096/1d826622-bc72-466f-8778-30dcaf773489", "number": 1, "id": "" }
];

利用map()方法迭代arr2,并更新每个对象的attachment属性:

arr2 = arr2.map((item, index) => ({
    ...item,
    attachment: arr1[index].attachment
}));

最终arr2将变为:

[
    {
        "attachment": "https://lumall.inspures.com/images/img/product/8e358701-177a-46e1-b25e-1e13fbcd92e0.png",
        "number": 0,
        "id": ""
    },
    {
        "attachment": "https://lumall.inspures.com/images/img/product/2adcd34a-786f-43ac-b8a8-3c45ed408019.png",
        "number": 1,
        "id": ""
    }
]

此方法简洁高效地完成了数组合并和键值替换,确保了数据的一致性和完整性。 需要注意的是,此方法假设arr1arr2具有相同长度。 如果长度不同,需要添加相应的错误处理机制。

来源:1740360061