5

Is there a better way to turn a destructured array into an object in Javascript?

I'm using the axios API library, and when I perform multiple queries at once I get back an array with 4-5 API responses. I then want to wrap those into an object and pass to another function. Maybe there's a one-liner? Not that this is really a big deal, but I have a bunch of these throughout my application.

const [foo, bar, baz] = [1, 2, 3]
const obj = { foo, bar, baz }
console.log(obj)
=> {foo: 1, bar: 2, baz: 3}
5
  • 2
    Are you looking for it without libraries? With Lodash you can do _.zipObject(['foo', 'bar', 'baz'], [1, 2, 3]) Commented Jan 26, 2017 at 1:01
  • Not necessarily without libraries. Was thinking there'd be a native JS way, but that's still pretty cool, thanks! Commented Jan 26, 2017 at 1:04
  • awesome that worked. thanks again @loganfsmyth. If anyone knows of a native JS version i'd be curious to see it Commented Jan 26, 2017 at 1:10
  • According here: you can configure your request to specify a responseType (see Request Config). You could use json as the responseType. Then in your js code, use JSON.parse so that the response is transformed into an object. Commented Jan 26, 2017 at 1:43
  • If you want to golf this into a one-liner, use console.log(( ([foo, bar, baz]) => ({ foo, bar, baz }) )([1, 2, 3])) Commented Mar 19, 2022 at 0:44

3 Answers 3

2

Util method toObj using Object.assign and map

const toObj = (arr, keys) =>
  Object.assign({}, ...keys.map((key, i) => ({ [key]: arr[i] })));  
  
const arr = [1, 2, 3]
const keys = ['foo', 'bar', 'baz'];

console.log(toObj(arr, keys));

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

Comments

0

There isn't really a shorter vanilla-only way than manually declaring the object and props. Lodash has a zipObject method that would do it though, e.g.

_.zipObject(['foo', 'bar', 'baz'], [1, 2, 3])

Comments

0

There's nothing built-in to JavaScript that does exactly what you want, but making a function that does it would be trivial. Here's one based on _.zipObject from Lodash:

function zipObject(props, values) {
  return props.reduce((object, prop, index) => {
    object[prop] = values[index];
    return object;
  }, {});
}

console.log(zipObject(['foo', 'bar', 'baz'], [1, 2, 3]));

As a golfed one-liner:

const zipObject = (ps, vs) => ps.reduce((o,p,i)=>(o[p]=vs[i],o),{});

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.