Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create object by grouping camelCase properties

Recently I've found that I have had to create a object from attributes on a HTML tag. I am doing this in a AngularJS environment, so hyphenated attributes are converted to camelCase, but I could also do the same using data- attributes and dataset

So for example I have:

<element person-name="Grant" animation-jump="123" />

Which gives the object

{
   "personName" : "Grant",
   "animationJump" : "123"
{

My problem is that I then want to convert that camelCase object into a structured object:

{
  "person" : {
    "name" : "Grant" },
  "animation" : {
    "jump" : "123" }
}

I've created a JSFiddle of my QUint Unit Test https://jsfiddle.net/gdt3bonw/ It's actually working for the case I want which is only 1 level, but I would like to get it working for any number of levels because I foresee that it will be needed and so I can release the code publicly.

like image 691
Luke T O'Brien Avatar asked Dec 18 '25 05:12

Luke T O'Brien


2 Answers

We will loop through the keys of the object using reduce, building up the result. We decompose each key into its components, such as personName into person and name. We loop over these components, creating subobjects if they do not already exist. Finally, we add the final component to the innermost subobject as a property with the value in question.

Object.keys(input).reduce((result, key) => {
  var parts = key.match( /(^|[A-Z])[a-z]+/g) . map(part => part.toLowerCase());
  var leaf = parts.pop();
  var obj = result;

  parts.forEach(part => obj = obj[part] = obj[part] || {});
  obj[leaf] = input[key];

  return result;
}, {});

You can't use that in this way, and I don't think that it would be a logic proposal. Below I explain why it wouldn't.

obj[["animation","jump"]] = "123"

replace it with

obj["animation"]["jump"] = "123"

and it's all fine.

Why I don't support your idea?

  • It's messy to use, there is no style in doing that.
  • There is no logic in using an array as an object key
  • There is another way of calling an object item by key: using a dot, and that won't support your idea. I think everyone can imagine why.
like image 32
boxHiccup Avatar answered Dec 20 '25 19:12

boxHiccup