0

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}))
...
2
  • 1
    Well First Name:"John" is a syntax error so is it actually "First Name":"John" Commented Mar 10, 2020 at 16:35
  • lodash.com/docs/4.17.15#mapKeys Commented Mar 10, 2020 at 16:36

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

This definitely helped me. Thank You!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.