Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

107
Vistas
How to merge 2 arrays of objects keeping only the new objects and getting the properties of the old objects?

I know there are dozens of questions titles similar to this one, but I couldn't find the one that solved my problem.

The point is that I'm avoiding unnecessary queries to the Database. So when the query is made, only what is needed is consumed. I get the data and merge it with LocalStorage to save usage.

I created this example to make it easier to read and help future users:

let usersDB = [
  { id: 1, name: 'John', age: 34 },
  { id: 2, name: 'Rose', age: 27 },
  { id: 3, name: 'Daniel', age: 40 },
]
const usersLS = [
  { id: 1, name: 'John', cars: ['BMW', 'Ferrari'] },
  { id: 2, name: 'Rose', cars: ['Tesla', 'Camaro'] },
  { id: 4, name: 'Ambrose', cars: ['Fiat'] },
]

/** Expected Result:
 * [
 *   {id: 1, name: 'John', cars: ['BMW', 'Ferrari']},
 *   {id: 2, name: 'Rose', cars: ['Tesla', 'Camaro']},
 *   {id: 3, name: 'Daniel'},
 * ]
 */

In the example above, userDB and userLS represent the Database and LocalStorage users, respectively.

Naturally, userDB is the most "updated", but userLS has a property "cars" which is not in the same table as the users in the database. So I need to update userLS using userDB as base, but without losing the "cars" property.

I know I could do a for...loop to iterate over users and within that, another for...loop to check if the id is the same and then generate a new array with the objects. However, I believe that there must be better ways to solve this problem.


Edit: What I have tried

let newArr = [];

for (let userDB of usersDB) {
  for (let userLS of usersLS) {
    if (userDB.id === userLS.id) {
      userDB.cars = userLS.cars
      newArr.push(userDB);
    }
  }
}
usersDB = Object.assign([...usersDB], ...newArr)

The code above is the way I am using to solve this problem. Can you think of a more direct solution?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You could use Array.map() on the usersDB array, then merge properties with any userLS found for any given user.

We'd use spread syntax to merge each item in the array(s):

const usersDB = [
  { id: 1, name: 'John', age: 34 },
  { id: 2, name: 'Rose', age: 27 },
  { id: 3, name: 'Daniel', age: 40 },
]

const usersLS = [
  { id: 1, name: 'John', cars: ['BMW', 'Ferrari'] },
  { id: 2, name: 'Rose', cars: ['Tesla', 'Camaro'] },
  { id: 4, name: 'Ambrose', cars: ['Fiat'] },
]

const result = usersDB.map(( { age, ...userDB}, idx) => { 
    let userLS = usersLS.find(u => u.id === userDB.id);
    return { ...userLS, ...userDB};
}, {})

console.log('Result:', result)
    
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

Array.map will help

Logic

  • Loop through usersDB array with Array.map
  • Find the matching node from usersLS array comparing the id
  • If the matching node found assign the cars property from that object to your return node from map function.

Working Fiddle

let usersDB = [
  { id: 1, name: 'John', age: 34 },
  { id: 2, name: 'Rose', age: 27 },
  { id: 3, name: 'Daniel', age: 40 },
]
const usersLS = [
  { id: 1, name: 'John', cars: ['BMW', 'Ferrari'] },
  { id: 2, name: 'Rose', cars: ['Tesla', 'Camaro'] },
  { id: 4, name: 'Ambrose', cars: ['Fiat'] },
];
const userConsolidated = usersDB.map((user) => {
  const usersLSnode = usersLS.find((item) => item.id === user.id);
  const { id, name } = user;
  const returnNode = { id, name };
  if (usersLSnode) returnNode.cars = usersLSnode.cars;
  return returnNode
});

console.log(userConsolidated);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda