问题描述
我在JavaScript中有一个构造函数,其中包含2个属性 Key
和 Values数组
:
I have a constructor in JavaScript which contains 2 properties Key
and Values array
:
function Test(key, values) {
this.Key = key;
this.Values = values.map(values);
}
然后我创建了一个 Test对象的数组
:
var testObjectArray = [];
testObjectArray.push(new Test(1, ['a1','b1']), new Test(2, ['a1','b2']));
现在我想将 testObjectArray
映射到单个键值
对数组,其类似于:
Now I want to map the testObjectArray
to single key-value
pair array which will be similar to :
[
{ "Key" : "1", "Value" : "a1" },
{ "Key" : "1", "Value" : "b1" },
{ "Key" : "2", "Value" : "a2" },
{ "Key" : "2", "Value" : "b2" },
]
如何使用数组的 map
函数实现这一目标?
How can I achieve this using array's map
function?
推荐答案
我想您是对map()的误解。这是一个非常简单的示例:
I guess you are misunderstanding map(). Here is a very simple example:
a = [1, 2, 3]
b = a.map(function (i) { return i + 1 })
// => [2, 3, 4]
以下是地图的MDN文档:。因此,您应该重新考虑map的用法。顺便说一句-您的示例不起作用,因为值不是函数。
Here is the MDN documentation for map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map. So you should rethink the usage of map in your case. By the way - your example is not working, because values is not a function.
这是一个可能的解决方案:
Here is a possible solution:
res = [];
a = [['a1','b1'],['a1','b2']];
for (var i = 0; i < a.length; ++i) {
for(var j = 0; j < a[i].length; ++j) {
res.push({"Key": i + 1 , "Value" : a[i][j]});
}
}
这篇关于如何将一个JavaScript数组映射到另一个JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!