ovatsug25
ovatsug25

Reputation: 8596

How to get a key to be used as a variable in a lodash map function?

I'm trying to restructure an object for convience.

This is the general structure:

 var dictionary = { "word": {"content": "wordy"}, "palabra": {"content":"palabrota" }};

I want it to look like this:

 [{"wordy":"word"},{"palabrota":"palabra"}]

And I'm trying this code out:

_.map(dictionary, function(v,k){ var new_key = v.content;return { new_key: k };} );

But instead of what I am expecting, this is the result:

[ { new_key: 'word' }, { new_key: 'palabra' } ]

How to get a key to be used as a variable in this function?

Upvotes: 2

Views: 1486

Answers (2)

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

You can use the _.invertBy method (as of LoDash v4.1.0), which will give you the key and an array of the values, thus ensuring the values aren't overwritten.

var dictionary = {
  "word": {"content": "wordy"},
  "anotherWord": {"content": "wordy"},
  "palabra": {"content":"palabrota" }
};

var result = _.invertBy(dictionary, function(item) {
  return item.content;
});

// "{"wordy":["word","anotherWord"],"palabrota":["palabra"]}"

EDIT: earlier response below. This works, however the limitation is duplicate content values would overwrite the keys. The docs for _.transform below shows how to generate an array to handle duplicates, and a similar setup can be used for the regular JS approach.

You can use the _.transform method:

var transformedResult = _.transform(dictionary, function(result, value, key) {
    return result[value.content] = key;
}); 

Or without LoDash at all, you can construct the object as intended.

var result = {};
Object.keys(dictionary).forEach(function(key) {
    var value = dictionary[key].content;
    result[value] = key;
});

Upvotes: 2

Retsam
Retsam

Reputation: 33389

I might recommend _.mapValues(dictionary, "content") for simplicity.

However, instead of [{"wordy":"word"},{"palabrota":"palabra"}], instead you'll get {"wordy": "word", "palabrota": "palabra"} as the result from _.mapValues. But given that you're using lodash, and lodash treats arrays and objects pretty much interchangeably, I think the non-array version would be more convenient.

Upvotes: 1

Related Questions