Skip to content

Instantly share code, notes, and snippets.

@khoand0000
Last active December 30, 2015 21:07
Show Gist options
  • Save khoand0000/4a906b4b7050e843b8a7 to your computer and use it in GitHub Desktop.
Save khoand0000/4a906b4b7050e843b8a7 to your computer and use it in GitHub Desktop.
Convert array of objects to object

I have array of objects like that

var arr = [
  { id: 4, name: 'John'},
  { id: 7, name: 'Mary'}
];

I want to convert it to object like that

{
  4: 'John',
  7: 'Mary'
}

There are 4 ways to achieve that

  • using .reduce: I like the way because .reduce is used and it is short frequently
_.reduce(arr, function(memo, value) { memo[value.id] = value.name; return memo;}, {});
  • using .map and .object: just reference, I don't remember how to use .object almost
_.chain(arr)
  .map(function(value) { return [value.id, value.name];})
  .object()
  .value();
  • using .pluck and .object: just reference, I don't remember how to use .object almost
_.object(_.pluck(arr, 'id'), _.pluck(arr, 'name'));
  • using .indexBy and .mapObject: just reference. It is long
_.chain(arr)
  .indexOf('id')
  .mapObject(function(value) { return value.name;})
  .value();

Remember, the function requires jQuery

_.mixin({
    fromFormSelector: fromFormSelector
});

/////////////////////

/**
 * convert form selector to JSON object
 * @param selector
 * @returns {*}
 */
function fromFormSelector(selector) {
    return _.reduceToObject($(selector).serializeArray(), 'name', 'value');
}

Usage

var data = _.fromFormSelector("#login-form"); // return {username: 'abc', password: ''}

I extends underscore the function to use future.

_.mixin({
    reductToObject: reductToObject
});

/////////////////////

/**
 * convert list of objects to object {item[key] : item[value]}
 * eg: [{id: 4, name: 'John'}, {id:7, name: 'Mary'}] ==> {4: 'John', 7: 'Mary'}
 * @param list
 * @param key
 * @param value
 * @returns {Object}
 */
function reduceToObject(list, key, value) {
    return _.reduce(list, function (memo, item) {
        memo[item[key]] = item[value];
        return memo;
    }, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment