从某个键中删除外部Object但保留内部对象

时间:2017-02-21 15:55:11

标签: javascript

您好我有以下对象:

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

它包含其他几个键,如size等...

如何在不删除内部内容的情况下摆脱"json",以便我的结果看起来像

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

我需要一种方法来删除每个包含字符串"json"的键而不删除包含的对象。

1 个答案:

答案 0 :(得分:0)

这是一个可能的解决方法,使用json然后value Object.assign(object,thingToUpdate)密钥更新包含delete内容作为直接json对的对象:< / p>

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