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

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

问题描述

我有以下数组:

<预><代码>[[val1, val2][val1, val2][val1, val2][valN, valN]]

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

<预><代码>[{纬度:val1,lng: val2},{纬度:val1,lng: val2},{纬度:valN,lng: valN}]

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

objectify(array) {返回 array.reduce(function(result, currentArray) {结果[currentArray[0]] = currentArray[1];返回结果;}, {});}

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

<预><代码>[{val1: val1, val2: val2}{val1: val1, val2: val2}{valN: valN, valN: valN}]

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

解决方案

您可以简单地使用 Array.prototype.map 通过应用投影函数将一个数组投影到另一个数组中:

var arrs = [[1, 2],[3, 4],[5, 6],[7, 8]];var objs = arrs.map(function(x) {返回 {纬度:x[0],lng: x[1]};});console.log(objs);

I have following array:

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

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}
]

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天全站免登陆