Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a javascript array to another javascript array

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?

like image 517
Tom Rider Avatar asked Oct 25 '12 21:10

Tom Rider


2 Answers

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]});
  }
}
like image 180
awenkhh Avatar answered Oct 13 '22 00:10

awenkhh


I'm sure there are other ways, but here's something with plain Javascript that does what you want:

http://jsfiddle.net/KXBRw/

function Test(key, values) {
    this.Key = key;
    this.Values = values;//values.map(values);
}

function getCombinedTests(testObjectArray) {
    var all = [];
    for (var i = 0; i < testObjectArray.length; i++) {
        var cur = testObjectArray[i];
        for (var j = 0; j < cur.Values.length; j++) {
            all.push({"Key": ""+cur.Key, "Value": cur.Values[j]});
        }
    }
    return all;
}

var testObjectArray1 = [];
testObjectArray1.push(new Test(1, ['a1','b1']), new Test(2, ['a1','b2']));

var combined = getCombinedTests(testObjectArray1);

console.log(combined);
like image 43
Ian Avatar answered Oct 13 '22 00:10

Ian