【问题标题】:Can destructuring assignment be used to effect a projection in CoffeeScript?可以使用解构赋值来影响 CoffeeScript 中的投影吗?
【发布时间】:2011-11-16 19:40:55
【问题描述】:

我在理解 CoffeeScript 中的解构赋值时遇到了一些麻烦。 documentation 包含几个示例,它们似乎暗示在分配期间重命名对象可用于投影(即映射、翻译、转换)源对象。

我正在尝试将a = [ { Id: 1, Name: 'Foo' }, { Id: 2, Name: '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

我将这个示例理解为从任意对象定义属性的选择,其中包括将数组的元素分配给变量。

更新:使用 thejh 的解决方案来展平嵌套对象数组

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

【问题讨论】:

    标签: javascript coffeescript destructuring


    【解决方案1】:

    b = ({x} for {Id: x} in a) 工作:

    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>
    

    【讨论】:

    • ({x:Id} for {Id} in a)({x:obj.Id} for obj in a) 更清晰一些。
    • 谢谢,这正是我想要的。
    【解决方案2】:

    CoffeeScript Cookbook 解决了与您完全相同的问题 - 解决方案是 map

    b = a.map (hash) -> { x: hash.id }
    

    list comprehension:

    c = ({ x: hash.id } for hash in a)
    

    您可以查看this fiddle online on CoffeScript homepage(使用console.info 显示结果)。

    编辑:

    为了使其具有破坏性,只需将映射变量 a 分配给自身:

    a = a1 = [ { Id: 1, Name: 'Foo' }, { Id: 2, Name: 'Bar' } ]
    a = a.map (hash) -> { x: hash.Id }
    console.info a;
    a1 = ({ x: hash.Id } for hash in a1)
    console.info a1;
    

    【讨论】:

    • 至少在第一个示例中,您可以省略花括号 ({})。
    • @thejh 是的,但我发现它们(卷曲)更具可读性和明确性,就像在第二个示例中一样;)
    猜你喜欢
    • 1970-01-01
    • 2020-04-30
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    相关资源
    最近更新 更多