【发布时间】:2018-05-26 19:28:30
【问题描述】:
我的最终目标是能够使用 spread operator 从 destructured 的对象分配一个新对象,同时分配默认值(如果它们不存在)。
看起来这可能不像我想要的那样。这是我的期望和尝试:
//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",
},
};
片段 1:不分配 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
片段 2:功能性,但如果需要多层嵌套,可能会出现问题。
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);
片段 2(显示嵌套对象未被覆盖)
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);
【问题讨论】:
-
你已经接近了,你只需要记住在使用扩展运算符时顺序很重要,因为后面的值会覆盖前面的值。试试
{ ...a, key3: { nestedKey1: "nestedVal1", ...a.key3, } } -
@Hamms 我已经更新了我的第二个 sn-p 以修复错误。我相信它会按预期运行。如果对象上已经存在一个值——>不要覆盖它。如果不存在,则使用默认值定义它(包括嵌套对象值而不覆盖其他预先存在的键)
标签: javascript json ecmascript-next