简体   繁体   中英

Javascript - Destructure an array into an object

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}

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));

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, eg

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

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),{});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM