Is it possible to assign an object when destructuring another (WHILE using defaults by default)

My ultimate goal is to assign a new object using the distribution operator from the destructured object when assigning default values ​​(if they do not exist).

It seems like it might not be possible as I like it. Here are my expectations and attempts:

//Expected beginning object
const a1 = {
  key1: "test1",
  key2: "test2",
};

//Expected end result
const b1 = {
  key1: "test1",
  key2: "test2",
  key3: {
    nestedKey1: "nestedVal1",
  },
};

//Expected beginning object
const a2 = {
  key1: "test1",
  key2: "test2",
  key3: {
    nestedKey1: "actualValue",
  }
}

//Expected end result
const b2 = {
  key1: "test1",
  key2: "test2",
  key3: {
    nestedKey1: "actualValue",
  },
};
Run code

Fragment 1: does not assign a value default.

const a = {
  key1: "test1",
  key2: "test2",
}

const {...b} = {
  key1,
  key2,
  key3: {
    nestedKey1: nestedKey1 = "nestedVal1",
  } = {},
  key4 = 'someDefault'
} = a

console.log(b); // does not have key3, or key4
console.log(key4); //this exists as a const, key3 does not
Run code

Fragment 2: functional, but can become problematic if several levels of nesting are required.

const a = {
  key1: "test1",
  key2: "test2",
}

let {
  key1,
  key2,
  key3: {
    nestedKey1: nestedKey1 = "nestedVal1",
  } = {},
} = a

const key3 = a.key3 || {}; // is it possible to include this in the destructuring? Specifically in the destructuring which defines the default.

const b = {
  key1,
  key2,
  key3: {
    ...key3,
    nestedKey1,
  }
}

console.log(b);
Run code

Snippet 2 (showing that nested objects are not overwritten)

const a = {
  key1: "test1",
  key2: "test2",
  key3: {
    someOtherKey: "itWorks",
  }
}

let {
  key1,
  key2,
  key3: {
    nestedKey1: nestedKey1 = "nestedVal1",
  } = {},
} = a

const key3 = a.key3 || {};

const b2 = {
  key1,
  key2,
  key3: {
    ...key3,
    nestedKey1,
  }
}

console.log(b2);
Run code
+4
source share

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


All Articles