【问题标题】:Replace an object that is inside of array if object id value from another array match如果来自另一个数组的对象 id 值匹配,则替换数组内部的对象
【发布时间】:2021-11-28 13:20:21
【问题描述】:

我有这个数组,其中的对象看起来像这样:

array1 = [
 0:{id:145, value:130000},
 1:{id:146, value:103300},
 2:{id:147, value:79500},
]

array2 = [
 0:{id:145, value:135000}
]

如果array2中对象的id与array1中对象的某个id匹配,我想替换数组中的对象

所以我希望是这样的:

array1 = [
 0:{id:145, value:135000},
 1:{id:146, value:103300},
 2:{id:147, value:79500},
]

我有这个代码

array1.splice(1, 1, array2[0])

但它返回给我这个:

array1 = [
 0:{id:145, value:135000},
 1:{id:145, value:130000},
 2:{id:146, value:103300},
 3:{id:147, value:79500},
]

任何帮助我将不胜感激

【问题讨论】:

    标签: javascript arrays typescript


    【解决方案1】:

    let array1 = [
     {id:145, value:130000},
     {id:146, value:103300},
     {id:147, value:79500},
    ]
    
    let array2 = [
     {id:145, value:135000},
     {id:147, value:135023}
    ]
        array2.map(x => {
        let index = array1.findIndex(d=> d.id === x.id)
      array1[index] = x  
    })
    console.log(array1)

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。您可以在帮助中心找到更多关于如何写好答案的信息:stackoverflow.com/help/how-to-answer。祝你好运?
    【解决方案2】:
    array2.forEach(i1 => {
        const index = array1.findIndex(i2 => i2.id == i1.id);
        if(index > -1) {
            array1.splice(index, 1, i1);
      }
    });
    

    【讨论】:

    • 你能解释一下为什么这行得通吗?
    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。您可以在帮助中心找到更多关于如何写好答案的信息:stackoverflow.com/help/how-to-answer。祝你好运?
    • 谢谢回答,两个回答都帮我,谢谢!
    猜你喜欢
    • 2022-11-21
    • 1970-01-01
    • 2020-08-06
    • 2020-09-29
    • 1970-01-01
    • 2019-04-14
    • 2015-03-31
    • 2020-02-21
    • 1970-01-01
    相关资源
    最近更新 更多