简体   繁体   English

用数组内部的对象破坏分配

[英]Destructuring Assignment with objects inside array

Is there a way to unpack values from an array of objects using destructuring assigments? 有没有一种方法可以使用解构赋值从对象数组中解压缩值?

[

{a : 1},
{a : 1},
{a : 1},
{a : 1}

]

The result I need here is an array: [1,1,1,1] 我在这里需要的结果是一个数组:[1,1,1,1]

Destructuring that would require the creation of 4 separate variables which would then get recombined into an array later. 解构将需要创建4个单独的变量,随后将它们重新组合成一个数组。 It would be very WET, and wouldn't make much sense, but if you had to: 这将是非常湿的,并且没有多大意义,但是如果您必须

 const arr = [ {a : 1}, {a : 1}, {a : 1}, {a : 1} ] const [{ a: item1 }, { a: item2 }, {a: item3}, {a: item4 }] = arr; const newArrOfAs = [item1, item2, item3, item4]; console.log(newArrOfAs); 

Your original code using reduce is better, but even more appropriate would be to use Array.prototype.map , since the input array and output array's items are one-to-one: 使用reduce原始代码更好,但更合适的方法是使用Array.prototype.map ,因为输入数组和输出数组的项是一对一的:

 const arr = [ {a : 1}, {a : 1}, {a : 1}, {a : 1} ] const newArrOfAs = arr.map(({ a }) => a); console.log(newArrOfAs); 

You could use the upcoming Array#flatMap 您可以使用即将推出的Array#flatMap

 var array = [{ a: 1 }, { a: 1 }, { a: 1 }, { a: 1 }]; result = array.flatMap(Object.values); console.log(result); 

You would use .map() : 您将使用.map()

 const a = [ { a: 1 }, { a: 1 }, { a: 1 }, { a: 1 } ]; const b = a.map(val => val.a); console.log(b); 

This should work. 这应该工作。 You can use foreach or map 您可以使用foreach或map

 const array = [ {a : 1}, {a : 1}, {a : 1}, {a : 1} ] let newArray = [] array.forEach(function(element) { newArray.push(element.a) }); console.log(newArray) 

You should just use map : 您应该只使用map

 const arr = [ {a : 1}, {a : 1}, {a : 1}, {a : 1} ]; const res = arr.map(({ a }) => a); console.log(res); 

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

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