繁体   English   中英

如何正确地将元素数组附加到对象数组

[英]How to properly append array of element to array of object

我的 React 代码中有这些数组和对象数组:

var A = [
  {id: 1, name: "han"},
  {id: 2, name: "mohd"},
]

var B = [100, 200];

我想将 B 附加到 A,以便输出变成这样:

var A = [
  {id: 1, name: "han", score: "100"},
  {id: 2, name: "mohd", score: "200},
]

我试着用下面的代码来做:

var newArray = [];

for (let k = 0; k < A.length; k++) {
        newArray = B.map(score => ({...A[k], score}));
}

return newArray;

但是,上面的代码在控制台记录时返回此输出:

newArray = [
  {id: 2, name: "mohd", score: "100"},
  {id: 2, name: "mohd", score: "200},
]

它只将元素附加到最新的对象,而不是所有对象。 有人知道我的代码有什么问题吗? 谢谢!

如果要使用map ,则不需要循环,因为map将遍历对象数组,并返回包含score属性的新对象的新数组。

使用回调的第二个参数 - 索引- 来确定我们应该添加b的哪个元素作为分数。

 const a = [ {id: 1, name: 'han'}, {id: 2, name: 'mohd'}, ]; const b = [100, 200]; // `map` over `a` making sure we get the object // in each iteration as well as its index const out = a.map((obj, i) => { // Create a new object adding in the // new `score` property using the element in `b` // that matches the index return { ...obj, score: b[i] }; }); console.log(out);

尝试这样的事情

const C = A.map((value, idx) =>({
   ...value,
   score: B[idx],
 }));

console.log(C)

如果您的两个数组长度相同,则使用此方法

 var A = [
      {id: 1, name: "han"},
      {id: 2, name: "mohd"},
    ]
    
    var B = [100, 200];
    console.log(A.map((x,i)=>
        {return {
            ...x,
        score:B[i]
        }
        }
                     ))

如果不确定关于使用这个例如..

var A = [
  {id: 1, name: "han"},
  {id: 2, name: "mohd"},
   {id: 2, name: "mohd"},
]

var B = [100, 200];
console.log(A.map((x,i)=>
    {return {
        ...x,
    score:!B[i]?0:B[i]
    }
    }
                 ))

输入数据结构不是很好......如果数组的大小不同怎么办?

使用您的数据模型:

var A = [
  {id: 1, name: "han"},
  {id: 2, name: "mohd"},
]

var B = [100, 200];
    
Object.entries(A).map((entry,i) => { 
  return {
    ...entry[1], //Object from A 
    score: B[i] // Get I index from B
   }
  })

理想数据模型

var B = [
 {id: 1, score:100 },
 {id: 2, score:200 }
]

并将 A 和 B 与 id 合并。

你试试那个方法。

let  A = [
    {id: 1, name: "han"},
    {id: 2, name: "mohd"},
  ]
  
  let  B = [100, 200];

  let newArray = [];
  let newObj ={};

  for(let i=0;i<A.length;i++){
    for(let j=0;j<B.length;j++){
        newObj = Object.assign(A[i],{score: B[j]})
    }
     newArray.push(newObj);
  }
console.log(newArray);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM