How to map a javascript array to another javascript array
arrays, javascript
Solution
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]
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]});
}
}
Problem
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); } ``` Then I created an array of `Test objects`: ``` var testObjectArray = []; testObjectArray.push(new Test(1, ['a1','b1']), new Test(2, ['a1','b2'])); ``` 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" }, ] ``` How can I achieve this using array's `map` function?