如何使用javascript覆盖现有对象

前端之家收集整理的这篇文章主要介绍了如何使用javascript覆盖现有对象 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想知道如何在对象中添加现有的匹配值并在javascript添加剩余的值
例如,我需要将merge_obj与ID为’1’的my_obj匹配,匹配值targetAmount仅替换,其余属性需要添加

我试过了

var filtervalue = my_obj.filter((e)=>e.id == "1").map((e)=>Object.assign({},e[0],merge_obj));

const merge_obj = {
  targetAmount: 50688.97,type: "REGULAR"
}

const my_obj = [
  {
    id: "1",logo: "img1.png",name: "fund",speed: "1 Days",targetAmount: "2000"
  },{
    id: "2",logo: "img2.png",name: "transfer",targetAmount: "3000"
  },]


Expected Output:
var my_obj = [
{
    id: "1",targetAmount: 50688.97,type: "REGULAR",},targetAmount: "3000",]
最佳答案
只需通过检查id合并第一个:

var my_obj = [{
    id: "1",]

var merge_obj = {
  targetAmount: 50688.97,type: "REGULAR"
};

var new_obj = my_obj.map(e => {
  if (e.id == "1") {
    Object.keys(merge_obj).forEach(key => e[key] = merge_obj[key]);
  }
  return e;
});
console.log(new_obj);
.as-console-wrapper { max-height: 100% !important; top: auto; }
原文链接:https://www.f2er.com/jquery/530876.html

猜你在找的jQuery相关文章