可以使用destructuring赋值来影响CoffeeScript中的投影吗? [英] Can destructuring assignment be used to effect a projection in CoffeeScript?
问题描述
我在CoffeeScript中理解解构赋值时遇到了一些麻烦。 文档包含几个示例,这些示例一起表示在分配期间重命名对象用来投影(即映射,翻译,转换)一个源对象。
I'm having some trouble understanding destructuring assignment in CoffeeScript. The documentation contains a couple of examples which together seem to imply that renaming objects during assignment can be used to project (i.e. map, translate, transform) a source object.
我试图项目 a = [{Id: Name:'Foo'},{Id:2,Name:'Bar'}] into
b = [{x:1},{x:2} code>。我试过下面没有成功;我明显误解了一些东西。任何人都可以解释这是否可能?
I am trying to project a = [ { Id: 1, Name: 'Foo' }, { Id: 2, Name: 'Bar' } ]
into b = [ { x: 1 }, { x: 2 } ]
. I've tried the following without success; I've clearly misunderstood something. Can anyone explain whether this is possible?
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的并行分配示例
CoffeeScript's Parallel Assignment Example
theBait = 1000
theSwitch = 0
[theBait, theSwitch] = [theSwitch, theBait]
b $ b
我理解这个例子意味着变量可以重命名,在这种情况下,它被用来执行交换。
I understand this example as implying that variables can be renamed which in this case is used to perform a swap.
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
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 = :x} in a)
works:
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>
这篇关于可以使用destructuring赋值来影响CoffeeScript中的投影吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!