1

Hi I have the following object:

{
  "position": {
    "json": {
      "left": "57px",
      "top": "79px"
    }
  },
}

It contains several other keys like size etc...

How can I get rid of the "json" without deleting the inner content so that my result looks like

{
  "position": {
    "left": "57px",
    "top": "79px"
  },
}

I need a way to remove every key that has a string "json" as content without removing the containing objects.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Viktor Carlson
  • 989
  • 1
  • 13
  • 36
  • Loop over the inner objects keys, add them to the outer object. When you're done, delete the outer object by it's key. There is no one-liner to say "delete the outer object key and just reassign all it's child key-values to it's parent object". Whatever happened to trying it and asking for help when you get stuck? – Adam Jenkins Feb 21 '17 at 15:56

1 Answers1

1

Here's a possible fix, update the object with contents of json as a direct value pair using Object.assign(object,thingToUpdate) and then delete the json key:

let objects = {
  "position": {
    "json": {
      "left": "57px",
      "top": "79px"
    }
  },
  "size": {
    "json": {
      "left": "57px",
      "top": "79px"
    }
  }
}

function removeJSONString(obj) {
  // store all keys of this object for later use
  let keys = Object.keys(obj);
  // for each key update the "json" key
  keys.map(key => {
    // updates only if it has "json"
    if (obj[key].hasOwnProperty("json")) {
      // assign the current obj a new field with "json" value pair
      Object.assign(obj[key], obj[key]["json"]);
      // delete "json" key from this object
      delete obj[key]["json"];
    }
  })
  // updated all fields of obj
  return obj;
}

console.log(removeJSONString(objects));
Jonathan Portorreal
  • 2,730
  • 4
  • 21
  • 38