-3

I am trying to combine these two object array into one object array with combining each property with their own values.

var a ={'a':[1,2,3,4],'b':[2,3,4,5]}

to [{'a':1,'b':2},{'a':2,'b':3},{'a':3,'b':4},{'a':4,'b':5}]

How can I achieve this using lodash library?

6
  • 2
    What have you tried so far? Commented Sep 10, 2019 at 15:00
  • Please don't ask for solutions without trying to solve the problem yourself first. If you have tried something, please share in your question what it is that you have tried. Commented Sep 10, 2019 at 15:02
  • I checked all the default lodash methods if any are there but couldnt find.. Commented Sep 10, 2019 at 15:02
  • Checked stackoverflow.com/questions/32100692/… But there the value is not an array so wanted a help how to do it throuh lodash Commented Sep 10, 2019 at 15:11
  • Lodash is a nice little toolbox but you don't necessarily have to use it. This is perfectly doable with a few lines of Javascript. Commented Sep 10, 2019 at 15:11

1 Answer 1

0

You need to iterate over the values for one of the keys, and then for each value—iterate over all the keys. This can be done in pure JavaScript fairly easily.

e.g. [ 1, 2, 3, 4 ] for key a, then loop over they keys: [ 'a', 'b' ]

Note: You will see the parameter '_' (underscore) used as the first parameter for the mapping below. This represents the current value in the list for the value of key 'a'. It is meaningless, but we need to have it there to access the next parameter (index of current value).

// Code Golf - zipObjects (100 bytes)
var z=a=>(x=>a[x[0]].map((_,i)=>x.reduce((o,k)=>Object.assign(o,{[k]:a[k][i]}),{})))(Object.keys(a))

function zipObjects(arr) {
  return (keys => {
    return arr[keys[0]].map((_, valueIndex) => {
      return keys.reduce((obj, key) => {
        return Object.assign(obj, {[key] : arr[key][valueIndex]});
      }, {});
    });
  })(Object.keys(arr));
}

console.log(zipObjects({ 'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5] }));
.as-console-wrapper { top: 0; max-height: 100% !important; }

With lodash

You can declare a plugin function very similarly.

_.mixin({
  'zipObjects' : function(arr) {
    return (keys => {
      return _.map(arr[_.head(keys)], (value, valueIndex) => {
        return _.reduce(keys, (obj, key) => {
          return _.assignIn(obj, {[key] : arr[key][valueIndex]});
        }, {});
      });
    })(_.keys(arr));
  }
});

console.log(_.zipObjects({ 'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5] }));
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.core.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.