LemonMan
LemonMan

Reputation: 3143

Basic coffeescript list comprehension with object

Suppose I have an object with the following format [Object object, Object object ...] where each object has the format {word: blah, word2: blahblah}

I know I can change the word and label to something else like this

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

However, I want to change it to this

{blah: blahblah} removing the labels and making each word in position of blah a key and each word in position of blahblah a value

Upvotes: 0

Views: 134

Answers (2)

hpaulj
hpaulj

Reputation: 231530

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' }

If you have underscore on hand, you could also use:

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

though that is the equivalent of:

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

Upvotes: 0

Ry-
Ry-

Reputation: 225054

I don’t think you can do it with a comprehension, but reduce works:

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

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

Upvotes: 1

Related Questions