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.

1
  • 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? Commented Feb 21, 2017 at 15:56

1 Answer 1

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));

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

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.