【问题标题】:How to add an property to an existing object inside an array如何将属性添加到数组内的现有对象
【发布时间】:2021-03-15 03:11:37
【问题描述】:

例如这是原始数组

[
 {name:xyz,id:123 },
 {name:abc,id:232},
] 

现在这是另一个数组

[
 {value:'anything'},
 {value:'anything12312'}
]

现在在新数组或原始数组中,输出应该是这个

[
 {value:'anything',name:xyz,id:123},
 {value:'anything12312', name:abc,id:232}}
]

我怎样才能做到这一点

【问题讨论】:

    标签: javascript html arrays object


    【解决方案1】:
    A1=[
        {name:"xyz",id:123 },
        {name:"abc",id:232},
       ];
    A2=[
        {value:'anyrhing'},
        {value:'anything12312'}
       ];
    
    obj1={
        ...A2[0],
        ...A1[0]}
    
    //another method to merge objects
    
    obj2=Object.assign(A2[1],A1[1]);
    
    //The result you needed
    
    A3=[obj1,obj2];
    

    【讨论】:

    • 请解释您的代码,不要只是将其作为答案发布,以便问题的作者更好地理解它
    【解决方案2】:

    使用对象解构。

    
    const arr1 = [
     {name:'xyz',id:123 },
     {name:'abc',id:232},
    ] 
    
    const arr2 = [
     {value:'anyrhing'},
     {value:'anything12312'}
    ]
    
    const arr3 = [];
    for(let i=0;i<arr1.length;i++)
      arr3.push({...arr2[i],...arr1[i]});
    

    【讨论】:

      【解决方案3】:

      你的意思是这样吗??

      map,index 和spread 用作:

      let a = [
       {name:"xyz",id:123 },
       {name:"abc",id:232},
      ]
      
      let b = [
       {value:'anyrhing'},
       {value:'anything12312'}
      ]
      
      let res = a.map((el,idx)=> ({...el,...b[idx]}));
      
      console.log(res)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-01-12
        • 2021-03-22
        • 2019-08-21
        • 1970-01-01
        • 2021-12-27
        • 2015-03-06
        相关资源
        最近更新 更多