简体   繁体   中英

Array to object one-liner

Is there a more succinct way of moving all array indices and values to an object than this:

arr = ["one","two","three"];
var rv = {};
for (var i = 0; i < arr.length; i++)
    rv[i] = arr[i];

I know you can iterate over the array and add to a new object one by one, but I hate adding a loop to my code whenever I want to switch between the two, particularly when providing answers here on SO (note that this means making a function is out, because this would bloat an answer just as much).

PS: I don't mind if your answer is frowned upon or is a misuse of a language feature, JS hackery fascinates me anyway. :)

Is there a succinct way of moving all array indices and values to an object as key value pairs?

They already are . Arrays in JavaScript are just objects, with properties named for the array indexes. They aren't really arrays at all in the classic computer science sense.

So you may well find that you don't need to do this most of the time. (Your use cases for it would be interesting.) But when you do, no, there's no particular shortcut. It's going to be a loop whatever you do, whether it's a loop in your code right out in the open, or something hidden underneath. Your code for doing it seems likely to be as good as any other.

这是一种hacky方式:

myArray.__proto__ = Object.prototype

As mentioned, arrays are objects too: typeof [] === 'object'

But anyway, try this:

function objectify(arr) {
    return arr.reduce({}, function (p, e, i) {
        p[i] = e;
        return p;
    });
}

It's not really cleaner than yours, but it avoids declaring i . For a faster function, move the anonymous function outside of objectify so it doesn't get recreated every time.

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