Javascript-将数组数组转换为具有预填充值的对象数组 [英] Javascript - convert array of arrays into array of objects with prefilled values
问题描述
我有以下数组:
[
[val1, val2]
[val1, val2]
[val1, val2]
[valN, valN]
]
N
表示这些数组不受限制的事实,即我永远不知道要存储多少数组.我试图完成的工作是使用键lat
和lng
将该数组转换为对象数组,我希望最终结果如下,以便可以将其用于其他需求:
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}
]
并不是我想要的,因为我真的需要这些lat
和lng
作为对象的键.我该如何解决这个问题?
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屋!