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

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;

但是,上面的代码 returns 在控制台登录时会输出以下内容:

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

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

如果您打算使用 map,您也不需要循环,因为 map 将遍历对象数组,并且 return 包含新对象的新数组包含 score 属性.

使用回调的第二个参数 - the index - 确定我们应该添加 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 }
]

并用 id 合并 A 和 B。

你用那个方法试试

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);