简体   繁体   English

我可以只使用扩展和解构赋值来做到这一点吗?

[英]Can I do this using only spread and destructuring assignment?

From this array of objects, I would like to create an array of the values of p .从这个对象数组中,我想创建一个p值的数组。 ie. IE。 ['a', 'b'] . ['a', 'b']

Can I do this using only spread and destructuring assignment?我可以只使用扩展和解构赋值来做到这一点吗?

const arr = [ {p:'a'}, {p:'b'} ]

e.g.

console.log(...arr.p) // not valid syntax

No, this is not a use case for spread syntax.不,这不是扩展语法的用例。 You should use the map method :您应该使用map方法

console.log(arr.map(o => o.p))

You can use destructuring in the parameter declaration to access the property, but it won't increase readability:您可以在参数声明中使用解构来访问属性,但不会增加可读性:

console.log(arr.map(({p}) => p))

The spread operator is the wrong thing to use in that case.在这种情况下使用扩展运算符是错误的。

You should use Array.map instead.您应该改用Array.map

const secondArr = arr.map((object) => object.p);
console.log(secondArr);

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

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