删除嵌套的JavaScript对象

时间:2018-06-27 15:37:37

标签: javascript

我一直试图从JavaScript对象中删除嵌套对象,但没有成功,也无法通过搜索以前的帖子来找到正确的答案。

这就是我一直想做的。

<code id='code'></code>

var myobj = {
  "children": [
    {
      "name": "albuterol ",
      "children": [
        {
          "name": "albuterol  - fluticasone ",
          "children": [
            {
              "name": "prednisone ",
              "children": [
                {
                  "name": "dexamethasone ",
                  "children": [],
                  "size": 1,
                  "colname": "CONCEPT_NAME.4"
                }
              ],
              "size": 3,
              "colname": "CONCEPT_NAME.3"
            }
          ],
          "size": 4,
          "colname": "CONCEPT_NAME.2"
        }]}]} 

function deleteObject(myobj) {
    var x = delete myobj.colname
    return (myobj.name, myobj.children)
}

document.getElementById('code').innerText = JSON.stringify(deleteObject(myobj))

我要删除对象colname。我是否缺少某些内容或代码完全不正确?

2 个答案:

答案 0 :(得分:3)

您需要一个递归函数才能删除该属性。

var myobj = {
  "children": [
    {
      "name": "albuterol ",
      "children": [
        {
          "name": "albuterol  - fluticasone ",
          "children": [
            {
              "name": "prednisone ",
              "children": [
                {
                  "name": "dexamethasone ",
                  "children": [],
                  "size": 1,
                  "colname": "CONCEPT_NAME.4"
                }
              ],
              "size": 3,
              "colname": "CONCEPT_NAME.3"
            }
          ],
          "size": 4,
          "colname": "CONCEPT_NAME.2"
        }]}]} 

function deleteColnameRecursive(obj){
  delete obj.colname
  if(obj.children){
     for(var i=0;i<obj.children.length;i++)
         deleteColnameRecursive(obj.children[i]);
  }
}

deleteColnameRecursive(myobj);

console.log(myobj);

答案 1 :(得分:-3)

MyObj没有直接的colname属性。 MyObj有一个名为Children的数组。

要删除适当的属性,请选择适当的对象。例如myObj.children[0].colname