Javascript-将数组数组转换为具有预填充值的对象数组 [英] Javascript - convert array of arrays into array of objects with prefilled values

查看:68
本文介绍了Javascript-将数组数组转换为具有预填充值的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组:

[
    [val1, val2]
    [val1, val2]
    [val1, val2]
    [valN, valN]
]

N表示这些数组不受限制的事实,即我永远不知道要存储多少数组.我试图完成的工作是使用键latlng将该数组转换为对象数组,我希望最终结果如下,以便可以将其用于其他需求:

N represents the fact that these arrays are not limited, i.e I never know how much of them do I store. What I try to accomplish is converting that array to array of objects with keys lat and lng and I expect so have final result as following so I can use it for further needs:

[
    {
        lat: val1,
        lng: val2
    },
    {
        lat: val1,
        lng: val2
    },
    {
        lat: valN,
        lng: valN
    }
]

我发现了一个将这些内部数组转换为对象的函数,它看起来像这样:

I found a function to convert these inner arrays to objects and it looks like this:

objectify(array) {
    return array.reduce(function(result, currentArray) {
        result[currentArray[0]] = currentArray[1];
        return result;
    }, {});
}

它可以工作,但输出看起来像这样:

It works but output looks like this:

[
    {val1: val1, val2: val2}
    {val1: val1, val2: val2}
    {valN: valN, valN: valN}
]

并不是我想要的,因为我真的需要这些latlng作为对象的键.我该如何解决这个问题?

and that's not what I'm looking for, because I really need these lat and lng to be keys of an object. How can I solve such issue?

推荐答案

您可以简单地使用

You can simply use Array.prototype.map to project an array into another one by applying a projection function:

var arrs = [
    [1, 2],
    [3, 4],
    [5, 6],
    [7, 8]
];

var objs = arrs.map(function(x) { 
  return { 
    lat: x[0], 
    lng: x[1] 
  }; 
});
console.log(objs);

这篇关于Javascript-将数组数组转换为具有预填充值的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆