简体   繁体   English

如何在Javascript中重建数组?

[英]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 : 否。使用map方法只能使用更简洁的符号:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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