A
A
Alex102142021-06-08 18:15:27
JavaScript
Alex10214, 2021-06-08 18:15:27

How to replace a value in an object by key?

Hello, I'm learning js and I have such a task.
I need to iterate over two objects and if they have the same keys, then I need to replace their value. Can you suggest how to do it?
Here is the first object:

a = {
      name: 'Alex',
      lastName: 'Ivanov',
      age: 20,
      email: '[email protected]',
      city: 'Moscow'
    };

Here is the second object:
b = {
      name: 'Ivan,
      lastName: 'Volkov',
      age: 18,
      email: '[email protected]',
      city: 'Moscow'
    };


I have to compare object A with object B and rewrite all keys from object B to object A. Please advise. It's hard for me, but I want to understand.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-06-08
@Alex10214

Object.keys(a).forEach(n => b.hasOwnProperty(n) && (a[n] = b[n]));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question