I am facing a challenge where I need to switch keys with values within an array of objects
var myArray = [
{'a' : {'x': ['Bob', 'Rob', 'Mike'], 'y': [4,5,6], 'name': 'a'}},
{'b' : {'x': ['Kris', 'Elen', 'Hanna'], 'y': [10,11,12], 'name': 'b'}}
]
The desired outcome is to swap the values of x and y in each object:
var myNewArray = [
{'a' : {'x': [4,5,6], 'y': ['Bob', 'Rob', 'Mike'], 'name': 'a'}},
{'b' : {'x': [10,11,12], 'y': ['Kris', 'Elen', 'Hanna'], 'name': 'b'}}
]
I attempted to iterate through the array and create a new one, but encountered an error message: Uncaught TypeError: Cannot read property 'name' of undefined
var test = [];
for (var i = 0; i < Object.keys(myArray).length; ++i) {
test['trace' + (i+1)] = {
name: myArray[i].name,
x: myArray[i].y,
y: myArray[i].x
};
}
I am seeking a dynamic solution as manually changing them is not feasible