2

I need to convert an array or an array of arrays to an object with keys named from an array of names. Example:

//given names
    names = ['first', 'second', 'third', 'fourth'] 
//array
    param = [1, 2, 3, 4] 
//becomes 
    result = {first: 1, second: 2, third: 3, fourth: 4}

//array of arrays 
    param = [
      [1, 2, 3, 4],
      [-4, 3, 1, 32],
    ]
//becomes
    result = [
      {first: 1, second: 2, third: 3, fourth: 4},
      {first: -4, second: 3, third: 1, fourth: 32},
    ]

My current solution is this:

    var names = ['first', 'second', 'third', 'forth'];

    function arrayToObject(array, names) {
      var result = {};
      for (var i = 0; i < array.length; i++) {
        if (typeof array[i] === 'object') {
          result[i] = arrayToObject(array[i], names);
          continue;
        }
        result[names[i]] = array[i];
      }
      return result;
    }

The problem with this solution is that it always returns an object, though it should return an array of objects when I pass in an array of arrays. Is there a way to do this with lodash and I'm not seeing it?

5
  • you mismatch copy and result. copy is not declared. Commented Mar 18, 2016 at 12:01
  • Fixed it, forgot to rename it Commented Mar 18, 2016 at 12:03
  • then it is ok. you declare result as object. write if statement: result = [] if array, result = {} if hash Commented Mar 18, 2016 at 12:03
  • Thanks, I knew that. That's why I'm asking for something like a lodash solution, for it to be as concise as possible :) Commented Mar 18, 2016 at 12:11
  • As I mentioned below, _.zipObject() is concise. Commented Mar 18, 2016 at 12:17

2 Answers 2

7

Vanilla JS: A function that creates an object from an array:

function toObj(arr) {
  return arr.reduce(function(p, c, i) {
    p[names[i]] = c;
    return p;
  }, {});
}

Used with map:

var out = arr.map(toObj);

DEMO

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

1 Comment

Clever, I didn't think of using map together with reduce
6

You can use _.zipObject() to zip up two arrays into an object. You are essentially mapping CSV data, with headers, to JavaScript objects.

You can try to search for JavaScript CSV converters. You may find some interesting results.

// Given names
var names = [ 'first', 'second', 'third', 'fourth' ]; 
// Array
var param = [ 1, 2, 3, 4 ];
// Becomes 
var result = _.zipObject(names, param);

document.body.innerHTML = JSON.stringify(result, null, 2);

// Array of arrays 
var param = [
  [ 1, 2, 3, 4 ],
  [ -4, 3, 1, 32 ],
];
// Becomes
var result = _.chain(param).map(function(p) {
	return _.zipObject(names, p)
}).value();

document.body.innerHTML += '\n\n' + JSON.stringify(result, null, 2);
body {
  font-family: monospace;
  white-space: pre;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.min.js"></script>

2 Comments

I'll look into CSV converters, thanks :). Though while this is indeed a solution in lodash I'll go with Andys solution due to it being as concise as yours and most importantly vanilla.
Well, I would have used reduce as well, as it is trivial, but you asked for a lodash solution...

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.