Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Object Key Zipping? #182

Open
Albert-IV opened this issue Nov 11, 2014 · 1 comment
Open

Object Key Zipping? #182

Albert-IV opened this issue Nov 11, 2014 · 1 comment
Labels
after modules This should be postponed until after modularization (temporary label, see #220) enhancement

Comments

@Albert-IV
Copy link

I didn't find any other requests similar to this, so forgive me if there has been one already.

Underscore supplies a method called zip, which is great. What I'm wanting is the ability to zip objects by their keys.

var before = {
  key1: ['val1', 'val2', 'val3'],
  key2: ['val4', 'val5', 'val6'],
  key3: ['val7', 'val8', 'val9']
};

var after = [
  {  key1: "val1",  key2: "val4",  key3: "val7"  },
  {  key1: "val2",  key2: "val5",  key3: "val8"  },
  {  key1: "val3",  key2: "val6",  key3: "val9"  }
]

I have something working for this, is there any interest in adding functionality like this to the repo? I can submit a PR if needed, just wanted to gauge interest before I start adding tests and getting my code styled correctly.

My first pass at implementation:

var zipObj = function( obj ) {
  var keys = Object.keys(obj);
  return _.zip.apply(_, keys.map(function(k, i) { return obj[k] || '' }))
  .map(function(d) { 
    var obj = {};

    keys.forEach(function(k, i) { obj[k] = d[i] });
    return obj;
  });
}
@Albert-IV
Copy link
Author

Just as a followup here, here is a more readable and more underscore-y method.

function zipObj(obj) {
  // First get keys from object.
  var keys = _.keys(obj);

  // For each key, grab the data
  var propertyArray = _.map(keys, function(k, i) { return obj[k] || undefined; });

  // "Shift" propertyArray around, so we can make into array of objects
  var zippedArray = _.zip.apply(_, propertyArray);

  // Set up function that will take an array,
  // Then use the keys variable to re-create.
  var createObject = function(d) {
    var rObj = {};

    _.each(keys, function(k, i) { rObj[k] = d[i]; });
    return rObj;
  };

  // For each item in zipped array, return an object
  return _.map(zippedArray, createObject);
}

Feel free to let me know of any issues you might have with a PR for this.

@jgonggrijp jgonggrijp added enhancement after modules This should be postponed until after modularization (temporary label, see #220) labels Aug 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
after modules This should be postponed until after modularization (temporary label, see #220) enhancement
Projects
None yet
Development

No branches or pull requests

2 participants