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/
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With