基本的coffeescript列表理解与对象

时间:2013-08-12 17:06:58

标签: javascript object coffeescript list-comprehension

假设我有一个格式为[Object object, Object object ...]的对象 其中每个对象的格式为{word: blah, word2: blahblah}

我知道我可以将这个词和标签更改为其他类似的内容

({text: o.label, weight: o.count} for o in data)

但是,我想将其更改为

{blah: blahblah}删除标签并将每个单词放在一个关键位置,并将blahblah中每个单词放在一个值

2 个答案:

答案 0 :(得分:1)

我认为你不能理解,但reduce有效:

data = [
    {key: 'hello', value: 'world'}
    {key: 'foo', value: 'bar'}
]

result = data.reduce(
    (obj, item) ->
        obj[item.key] = item.value
        obj
    {}
)

答案 1 :(得分:0)

data = [{word: 'blah1', word2: 'blahblah1'},
        {word: 'blah2', word2: 'blahblah2'}]
y = {}; for o in data then y[o.word] = o.word2
y
# { blah1: 'blahblah1', blah2: 'blahblah2' }

如果您手头有underscore,也可以使用:

_.object([o.word,o.word2] for o in x)

虽然这相当于:

y={}; y[z[0]]=z[1] for z in ([o.word,o.word2] for o in x)