[英]Destructuring for get the first property of an object?
For arrays, we can define the properties depending on it's indexes like: 对于数组,我们可以根据其索引定义属性,例如:
const arr = [1, 2, 3]; const [first, second, third] = arr; console.log(first, second, third)
I'm just wondering if there's a possible solution to do it's reverse with objects like: 我只是想知道是否有可能的解决方案来解决类似这样的问题:
const obj = {first: "a", second: "b", third: "c"} const {0, 1, 2} = obj; //expected: "a", "b", "c"
It isn't. 不是。
Objects are not designed to be ordered, so there isn't a first property per se. 对象不是按顺序设计的,因此本身没有第一个属性。
You could convert an object into an array of its values first … 您可以先将一个对象转换为其值的数组……
const obj = { first: "a", second: "b", third: "c" } const array = Object.values(obj); const [foo, bar, baz] = array; console.log({ foo, bar, baz });
… but it is unlikely to be useful and it certainly wouldn't be intuitive code that is easy to maintain. …但是它不太可能有用 ,并且肯定不是易于维护的直观代码。
You do it like this for objects: 您可以对对象执行以下操作:
const obj = {foo: 123, bar: 'str'}
const {foo, bar} = obj
Try this: 尝试这个:
const obj = {first: "a", second: "b", third: "c"}
const indexes = [0, 1, 2]
indexes.map( (val) => { return Object.values(obj)[val] } ) //["a", "b", "c"]
You could take the values and assign this to an array for destructuring. 您可以采用这些值,并将其分配给数组以进行解构。
The order is actually dtermined by the insertation order or if a key is like a valid index of an array, it is sorted numerically to top. 该顺序实际上是由插入顺序确定的,或者如果键像数组的有效索引一样,则将其按数字排序到顶部。
const object = { first: "a", second: "b", third: "c" }, [first, second, third] = Object.values(object); console.log(first, second, third);
For extracting a an arbitrary position, you vould take an object with an index an object property assignment pattern [YDKJS: ES6 & Beyond] for a new valid variable. 为了提取任意位置,您可以将带有索引的对象作为对象属性分配模式[YDKJS:ES6&Beyond]用于新的有效变量。
const object = { first: "a", second: "b", third: "c" }, { 2: foo } = Object.values(object); console.log(foo);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.