Reputation: 157
I have been struggling with changing the column name from the array of objects. One of the column name contain spaces.
var array = [{"First Name":"John", "Last Name":"Doe", "age":46}, {"First Name":"Tim", "Last Name":"Jones", "age":26}, {"First Name":"Marcus", "Last Name":"Brown", "age":31}, {"First Name":"Paul", "Last Name":"Daniels", "age":28}];
I want to change the object column name to firstName or first_name so the array could be the following:
var array = [{"first_name":"John", "Last Name":"Doe", "age":46}, {"first_name":"Tim", "Last Name":"Jones", age:26}, {"first_name":"Marcus", "Last Name":"Brown", "age":31}, {"first_name":"Paul", "Last Name":"Daniels", "age":28}];
I tried mapping like this, but it didn't work since i can do that inside a map function:
...
.map(({ [First Name], age}) => ({ [First Name], age}))
...
I want to change the column name before mapping it so I would do something like this:
...
.map(({ first_name, age}) => ({ first_name, age}))
...
Upvotes: 0
Views: 56
Reputation: 5542
According to the comments, I modified your JSON to be valid, now you can loop over it and create a new object with the desired results:
let array = [{"First Name": "John", "Last Name":"Doe", age:46}, {"First Name":"Tim", "Last Name":"Jones", age:26}, {"First Name":"Marcus", "Last Name":"Brown", age:31}, {"First Name":"Paul", "Last Name":"Daniels", age:28}];
let modifiedArray = array.map(item => {
return {
first_name: item["First Name"],
"Last Name": item["Last Name"],
age: item.age
}
});
console.log(modifiedArray);
I hope it helps!
Upvotes: 1