2

I'm populating some fields using JSON. The keys I load are all camel cased and look something like the below...

{
  "ThisIsAnother": {},
  "ThisIsAnExample": {}
}

I'm pulling them back fine, but I need to format them to make them correct, something like

{
  "This Is Another": {},
  "This Is An Example": {}
}

Is this possible with JS or should I format my JSON in another way?

3
  • 1
    Can you be more specific then I need to format them? Commented Feb 1, 2019 at 14:13
  • Sorry, amended @AshayMandwarya Commented Feb 1, 2019 at 14:14
  • is that an array of objects like this ? Commented Feb 1, 2019 at 14:32

3 Answers 3

5

You can always split on capital casing of all keys for your object. Though, I believe users should adapt and use proper json key naming.

let data = {
  "ThisIsAnother": {}
};

Object.keys(data).forEach((key) => {
  let newKey = key.split(/(?=[A-Z])/).join(" ");
  data[newKey] = data[key];
  delete data[key];
});

console.log(data);

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

2 Comments

Thanks @JonathanHamel, what do you mean adapt and use proper json key naming?
Proper key could be "thisIsAnother" in that case. google.github.io/styleguide/…
0

You could use a regex with a capture group for [A-Z] to replace them with an extra space

(Note: This creates a new object. If you want the same object mutated, you can use this regex with what accepted answer is suggesting)

let data = {
  "ThisIsAnother": {},
  "ThisIsAnExample": {}
};

const newObj = Object.keys(data).reduce((acc, k) => {
  let newKey = k.replace(/\B([A-Z])/g, " $1");
  acc[newKey] = data[k];
  return acc
},{});

console.log(newObj);

Comments

0

const json = {
  ThisIsAnExample: {},
  ThisIsAnother: {}
};

const result = Object.entries(json).reduce((all, [key, value]) => {
  all[key.match(/[A-Z][a-z]+/g).join(" ")] = value

  return all;
}, {});

console.log(result);

Comments

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.