0

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

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

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

但是,我想将其更改为

{blah: blahblah}删除标签并使 blah 位置的每个单词成为键,并让 blahblah 位置的每个单词成为值

4

2 回答 2

1

我认为您无法通过理解来做到这一点,但是reduce可以:

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

result = data.reduce(
    (obj, item) ->
        obj[item.key] = item.value
        obj
    {}
)
于 2013-08-12T17:15:22.220 回答
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)
于 2013-08-13T05:48:54.213 回答