简体   繁体   中英

How to rebuild an array in Javascript?

I have an array that's like this:

[
    [ "bar1", "bar2" ],
    [ "bar1", "bar2" ],
    [ "bar1", "bar2" ]      
]

I'd like to rebuild with named properties, like this:

[
    { foo1: "bar1", foo2: "bar2" },
    { foo1: "bar1", foo2: "bar2" },
    { foo1: "bar1", foo2: "bar2" }
]

Currently I am manually looping through the array and building a new one. But is there a better way to do this?

Thanks!

Currently I am manually looping through the array and building a new one. But is there a better way to do this?

No. Only more concise notation, using the map method :

var arr2 = arr1.map(function(a) {
    return {foo1: a[0], foo2: a[1]};
});

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