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:
const a1 = {
key1: "test1",
key2: "test2",
};
const b1 = {
key1: "test1",
key2: "test2",
key3: {
nestedKey1: "nestedVal1",
},
};
const a2 = {
key1: "test1",
key2: "test2",
key3: {
nestedKey1: "actualValue",
}
}
const b2 = {
key1: "test1",
key2: "test2",
key3: {
nestedKey1: "actualValue",
},
};
Run codeFragment 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);
console.log(key4);
Run codeFragment 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 || {};
const b = {
key1,
key2,
key3: {
...key3,
nestedKey1,
}
}
console.log(b);
Run codeSnippet 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
source
share