简体   繁体   English

如何在javascript中从对象内部解构数组?

[英]How to destructure an array from inside an object in javascript?

I have an object like this: 我有一个这样的对象:

obj = {'id': 1, a: [1, 2, 3]}

I want to destructure and get the array a from obj 我想解构并从obj获取数组a

arr = {...obj.a}

I get: 我得到:

{0: 1, 1: 2, 2: 3}

which is not an array 这不是数组

How to get the array itself ? 如何获得数组本身?

You are spreading an array inside {} . 您正在{}传播数组。 This creates an object with indices of the array as keys. 这将创建一个以数组索引为键的对象。 This is why you get {0: 1, 1: 2, 2: 3} 这就是为什么您得到{0: 1, 1: 2, 2: 3}

 const a = [ 1, 2 ] console.log({ ...a }) 

If you want to get a property into a variable, this is the correct syntax : 如果要将属性放入变量,则这是正确的语法

const { propertyName } = yourObject
// if you want to have a variable name which is different than the propertyName
const { propertyName: someOtherVariable } = yourObject

Here's the working snippet: 这是工作片段:

 const obj = {'id': 1, a: [1, 2, 3] } const { a: arr } = obj; // this is same as: const arr = obj.a console.log(arr) 

You could destructure to an array by assigning the array to an array with a rest syntax. 您可以通过使用rest语法将数组分配给数组来将其分解为数组。

 var obj = { id: 1, a: [1, 2, 3] }, [...arr] = obj.a; console.log(arr); 

差不多-相反:)

let {a: arr} = {'id': 1, a: [1, 2, 3]}

Use brackets instead of curly braces to spread it into a new array: 使用方括号而不是花括号将其传播到新数组中:

 const obj = {'id': 1, a: [1, 2, 3]} const arr = [...obj.a] console.log(arr) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM