How is a JavaScript array and object transposed? Specifically, I am trying to convert the follow x and y array/objects to the new desired x_new and y_new array/objects.
Given
var x=['x1','x2','x3'];
var y=[
{name:'y1',data:['x1y1','x2y1','x3y1']},
{name:'y2',data:['x1y2','x2y2','x3y2']}
];
console.log(x,y);
Desired
var new_x=[
{name:'x1',data:['x1y1','x1y2']},
{name:'x2',data:['x2y1','x2y2']},
{name:'x3',data:['x3y1','x3y2']}
];
var new_y=['y1','y2'];
console.log(new_x,new_y);
Below is what I attempted.
var _x=[],_y=[];
for (var i = 0; i < y.length; i++) {
_y.push(y[i].name);
var data=[];
for (var j = 0; j < y[i].data.length; j++) {
data.push(y[i].data[j]);
}
_x.push({name:y[i].name,data:data});
}
console.log(_x,_y)
asked Aug 7, 2016 at 15:16
user1032531
26.5k77 gold badges248 silver badges422 bronze badges
1 Answer 1
Easy using some maps:
var x = ['x1','x2','x3'];
var y = [
{name:'y1', data:['x1y1','x2y1','x3y1']},
{name:'y2', data:['x1y2','x2y2','x3y2']}
];
var new_x = x.map((str, i) => ({
name: str,
data: y.map(obj => obj.data[i])
}));
var new_y = y.map(obj => obj.name);
console.log(new_x, new_y);
If you don't want arrow functions it's a bit more verbose.
var x = ['x1','x2','x3'];
var y = [
{name:'y1', data:['x1y1','x2y1','x3y1']},
{name:'y2', data:['x1y2','x2y2','x3y2']}
];
var new_x = x.map(function(str, i) {
return {
name: str,
data: y.map(function(obj) {
return obj.data[i];
})
};
});
var new_y = y.map(function(obj) {
return obj.name;
});
console.log(new_x, new_y);
Or, if you prefer your loop approach,
var x = ['x1','x2','x3'];
var y = [
{name:'y1', data:['x1y1','x2y1','x3y1']},
{name:'y2', data:['x1y2','x2y2','x3y2']}
];
var new_x = new Array(x.length),
new_y = new Array(y.length);
for (var i = 0; i < x.length; i++) {
var data = new Array(y.length);
for (var j = 0; j < y.length; j++)
data[j] = y[j].data[i];
new_x[i] = {name: x[i], data: data};
}
for (var j = 0; j < y.length; j++)
new_y[j] = y[j].name;
console.log(new_x, new_y)
answered Aug 7, 2016 at 15:25
Oriol
291k71 gold badges459 silver badges535 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
user1032531
Thanks Oriol, I was thinking/hoping some sort of map function would work even though they baffle me a bit. Looking at your solution, however, it doesn't seem that baffling.
user1032531
Do you mind explaining what the "arrow functions" are doing?
Kiran Yallabandi
@user1032531 The arrow functions are just anonymous functions declared using fat arrow syntax. developer.mozilla.org/en/docs/Web/JavaScript/Guide/…
Ruan Mendes
They are one line fat arrow functions, it's as if it was
y.map(obj => { return obj.data[i])} , which is the same as y.map(function(obj) => { return obj.data[i])} ,user1032531
Thanks all. I think for now I will stick with the non-arrow functions until I get a little better.
lang-js