My ultimate objective is to effortlessly create a new object by utilizing the spread operator from an object that has been destructured while assigning default values, if they are absent.
It seems like achieving this goal might not be as straightforward as I had hoped. Here are my expectations and attempts:
// Initial object
const firstObj = {
key1: "test1",
key2: "test2",
};
// Desired end result
const finalObj = {
key1: "test1",
key2: "test2",
key3: {
nestedKey1: "nestedVal1",
},
};
// Initial object
const secondObj = {
key1: "test1",
key2: "test2",
key3: {
nestedKey1: "actualValue",
}
}
// Desired end result
const thirdObj = {
key1: "test1",
key2: "test2",
key3: {
nestedKey1: "actualValue",
},
};
Snippet 1: Does not set default values.
const initialObject = {
key1: "test1",
key2: "test2",
}
const { ...newObject } = {
key1,
key2,
key3: {
nestedKey1: nestedKey1 = "nestedVal1",
} = {},
key4 = 'someDefault'
} = initialObject
console.log(newObject); // lacks key3 and key4
console.log(key4); // key4 exists as const, but key3 does not
Snippet 2: Functional, but may pose challenges with multiple levels of nesting.
const startingObj = {
key1: "test1",
key2: "test2",
}
let {
key1,
key2,
key3: {
nestedKey1: nestedKey1 = "nestedVal1",
} = {},
} = startingObj
const key3 = startingObj.key3 || {};
const resultingObj = {
key1,
key2,
key3: {
...key3,
nestedKey1,
}
}
console.log(resultingObj);
Snippet 2 (illustrating that nested objects remain untouched)
const obj = {
key1: "test1",
key2: "test2",
key3: {
someOtherKey: "itWorks",
}
}
let {
key1,
key2,
key3: {
nestedKey1: nestedKey1 = "nestedVal1",
} = {},
} = obj
const nestedKey3 = obj.key3 || {};
const newObj = {
key1,
key2,
key3: {
...nestedKey3,
nestedKey1,
}
}
console.log(newObj);