Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda