gpt4 book ai didi

javascript - 如何在一行中析构对象和该对象的属性?

转载 作者:行者123 更新时间:2023-12-03 01:10:33 26 4
gpt4 key购买 nike

我经常使用析构函数将对象拆分为多个部分:

const foo = {
a: "part 1",
b: "part 2",
c: "part 3",
}

//get a,b,c
const ({a,b,c}) = foo;

console.log(a,b,c) // "part 1, part 2, part 3"

我有时还使用析构函数来获取对象的属性部分:

const foo = {
a: "part 1",
b: "part 2",
c: "part 3",
d: {
a: "part a from d",
b: "part b from d",
c: "part c from d",
}
}

//just get a from d
const ({d: {a}}) = foo; // I split out a here but not d

console.log(a) // "part a from d"
console.log(d) // d is not defined but I want d here

我怎样才能得到d这里a、b、c可以在同一行吗?

最佳答案

  const { d, d: { a } = {} } = foo

只需解构两次即可。或者解构两次:

const {d} = foo;
const {a} = d || {};

关于javascript - 如何在一行中析构对象和该对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52227677/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com