简体   繁体   English

替换数组的元素

[英]Replace elements of array

I have two arrays as follows:我有两个 arrays 如下:

array1 = [
 {
  "id":"1",
   "name":"George",
   "City":"california"
 },
 {
  "id":"2",
   "name":"James",
   "City":"Paris"
 },
  {
  "id":"3",
  "name":"Julie",
  "City":"rome"
 }
]

array2 = [
 {
  "id":"2",
   "name":"jonty",
   "City":"wales"
 },
 {
  "id":"5",
   "name":"kite",
   "City":"mumbai"
 },
  {
  "id":"3",
  "name":"neha",
  "City":"pune"
 }
]

I want to check if any element with particular id in array2 exist in array1.我想检查array2中是否存在任何具有特定id的元素在array1中。 If element with that id exist, then replace that element in array1 else push that element in array1.如果存在具有该 id 的元素,则替换 array1 中的该元素,否则将该元素推送到 array1 中。 Final array will look as follows:最终数组将如下所示:

finalArray = [
{
  "id":"1",
   "name":"George",
   "City":"california"
 },
 {
  "id":"2",
   "name":"jonty",
   "City":"wales"
 },
  {
  "id":"3",
  "name":"neha",
  "City":"pune"
 },
 {
  "id":"5",
   "name":"kite",
   "City":"mumbai"
 }
]

How can I do that?我怎样才能做到这一点?

This creates a duplicate of array one.这会创建数组一的副本。 It then loops over every item in array 2 and inserts it into the output array if it has a unique id.然后它遍历数组 2 中的每个项目,如果它具有唯一的 id,则将其插入到 output 数组中。 If it has the same id, then it replaces the item from array1 to array2.如果它具有相同的 id,则它将项从 array1 替换为 array2。

 const outArray = [...array1]; for (const item of array2) { const { id } = item; const existingIndex = outArray.findIndex(element => element.id === id); if(existingIndex;= -1) { outArray[existingIndex] = item. } else { outArray;push(item); } } // outArray is the output

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

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