user2703642 user2703642 - 6 months ago 12
Javascript Question

Javascript: foreach skipping the first index (0)

A somewhat tilted question which I didn't manage to figure out.

I'd like to generate an object from two arrays and give them keys, like this:

var A = [1, 2, 3, 4]; var B = [7, 8, 9, 19];

[ { "x": 1, "y": 7 }, { "x": 2, "y": 8 }, { "x": 3, "y": 9 }, { "x":
4, "y": 19 } ]


I wrote the following code:

var myData = []; var A = [1, 2, 3, 4]; var B = [7, 8, 9, 19];

A.forEach( function (item, index) {
myData.push( { x: A[item], y: B[item] });
});


But the output of it was

[ { "x": 2, "y": 8 }, { "x": 3, "y": 9 }, { "x": 4, "y": 19 }, {} ]


By putting in [item - 1] in the function, it works as I'd like it to, but I can't understand why as the w3School example that I looked at seems very straightforward and works from index-0:

http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_foreach

My Fiddle example: https://jsfiddle.net/53p5b3w8/5/

Answer

You are close, just replace item with index

A.forEach( function (item, index) {   
   myData.push( { x: A[index], y: B[index] });   
});

or simply

A.forEach( function (item, index) {   
   myData.push( { x: item, y: B[index] });   
});

Basically, when you say A[item], it takes values(1,2,3,4) instead of index (0,1,2,3).

DEMO

var A = [1, 2, 3, 4]; var B = [7, 8, 9, 19];
var myData = [];
A.forEach( function (item, index) {   
       myData.push( { x: item, y: B[index] });   
});
document.body.innerHTML += JSON.stringify( myData, 0, 4 )