Simon Breton Simon Breton - 1 year ago 75
Javascript Question

How do I go from this ["url", "395868"] to this [name: "url", value: "395868"]

I'm beginning with javascript and I feel like I don't have too much vocabulary to explain my issue. I'm trying to build a chart with d3 and here is the data I need :

{x: 'A', y: 10},
{x: 'B', y: 5},
{x: 'C', y: 15}

but right now here is what I have

So... how do I merge my data and how do I add the "x" and "y" categories name.

Answer Source

Here is some ES6 code that transforms the one to the other:

var data = [['A',10],['B',5],['C',15]];

var result = ([x, y]) => ({ x, y }) );


Explanation the map method will go through each element of data (there are 3 elements), and call the function you provide it as argument. That function will thus be called three times, and each time it will be passed the current element as argument.

(...) => .... this is the ES6 arrow syntax. It represents a function, but with some different rules. These differences are not relevant in this answer, so I wont go into that.

[x, y]: this is the argument given by map: it is one of the array elements. Normally you would have just one variable here (or several separated by commas), but here we use a "destructuring assignment": we expect the argument to be an array, and want to assign its elements to variables x and y. So the first time x will have the value "A", and y will be 10, ...etc.

=>: the arrow of the arrow function. What follows is the expression that will be returned by the function.

({ x, y }): the parentheses are only necessary to avoid confusion with a statement block, which also starts with a brace. The { x, y } is the object to return. Here again we use ES6 syntax which actually interprets this as { "x": x, "y": y }; it's a shortcut notation.

So the map method will call the function three times, and each time an object is returned. map will put these in a new array, and return that array.

Here is similar code in ES5 syntax:

var data = [['A',10],['B',5],['C',15]];

result = {
    return { x: arr[0], y: arr[1] };


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download