Is there a purely functional way to merge objects in JavaScript?

Let's say I have an object with some properties:

const obj = {
  key1: 1
  key2: 2
}

and I have a function someFuncthat takes a single object as a parameter. I want to pass objwith some additional parameters, for example

someFunc({
  key1: 1
  key2: 2
  otherKey: 3
})

The problem is that I do not want to change the state obj. After it has someFuncbeen called, it should not contain otherKeyas a property.

This leaves Object.assignout the question:

let ident = someObj => someObj;

ident(Object.assign(obj, {otherKey: 3}))
console.log(someObj); // -> {key1: 1, key2: 2, otherKey: 3}

Creating a new variable and assigning it otherKey = 3does the same.

I know that I can use some kind of deep duplication, but this seems like an overly complicated way to solve a rather simple problem.

- , obj1, obj2, , Object.assign(obj1, obj2), . JS, , - ?

+4
2

Object.assign - obj :

ident(Object.assign({otherKey: 3}, obj))

, obj, .

+6

. - ES6:

const obj1 = {
  key1: 1,
  key2: 2,
}

const obj2 = {
  key1: 1,
  key2: 12,
  otherKey: 3
};

const merged = { ...obj1, ...obj2 };

console.log('merged: ', merged);
console.log('obj1: ', obj1);
console.log('obj2: ', obj2);
Hide result

, obj1, obj2

+1

Source: https://habr.com/ru/post/1691156/


All Articles