我在理解CoffeeScript中的解构赋值时遇到了一些麻烦. documentation包含几个示例,这些示例似乎一起暗示在分配期间重命名对象可用于投影(即映射,转换,变换)源对象.
我试图将a = [{Id:1,名称:’Foo’},{Id:2,名称:’Bar’}]投影到b = [{x:1},{x:2}].我试过以下但没有成功;我明显误解了一些事情.任何人都可以解释这是否可能?
我的穷人试图不归[[x:1},{x:2}]
a = [ { Id: 1, Name: 'Foo' }, { Id: 2, Name: 'Bar' } ]
# Huh? This returns 1.
x = [ { Id } ] = a
# Boo! This returns [ { Id: 1, Name: 'Foo' }, { Id: 2, Name: 'Bar' } ]
y = [ { x: Id } ] = a
# Boo! This returns [ { Id: 1, Name: 'Foo' }, { Id: 2, Name: 'Bar' } ]
z = [ { Id: x } ] = a
CoffeeScript的并行分配示例
theBait = 1000
theSwitch = 0
[theBait, theSwitch] = [theSwitch, theBait]
我理解这个例子意味着可以重命名变量,在这种情况下用于执行交换.
CoffeeScript的任意嵌套示例
futurists =
sculptor: "Umberto Boccioni"
painter: "Vladimir Burliuk"
poet:
name: "F.T. Marinetti"
address: [
"Via Roma 42R"
"Bellagio, Italy 22021"
]
{poet: {name, address: [street, city]}} = futurists
我理解这个例子是从任意对象定义一系列属性,包括将数组元素分配给变量.
更新:使用jh的解决方案来展平嵌套对象数组
a = [
{ Id: 0, Name: { First: 'George', Last: 'Clinton' } },
{ Id: 1, Name: { First: 'Bill', Last: 'Bush' } },
]
# The old way I was doing it.
old_way = _.map a, x ->
{ Id: id, Name: { First: first, Last: last } } = x
{ id, first, last }
# Using thejh's solution...
new_way = ({id, first, last} for {Id: id, Name: {First: first, Last: last}} in a)
console.log new_way
解决方法:
b =(对于{Id:x}中的{x})有效:
coffee> a = [ { Id: 1, Name: 'Foo' }, { Id: 2, Name: 'Bar' } ]
[ { Id: 1, Name: 'Foo' },
{ Id: 2, Name: 'Bar' } ]
coffee> b = ({x} for {Id: x} in a)
[ { x: 1 }, { x: 2 } ]
coffee>