如何通过javascript从json结构中删除没有其值的元素?

时间:2019-06-15 16:03:07

标签: javascript json xml

这是我所拥有的结构,我已从xml转换为json,但现在我不需要根元素和 element 标签:

{
"root": {
    "batchRequests": [
        {
            "element": {
                "method": "PATCH",
                "url": "url",
                "richInput": {
                    "Error_Message__c": {},
                    "Status__c": "0"
                }
            }
        },
        {
            "element": {
                "method": "PATCH",
                "url": "url",
                "richInput": {
                    "Error_Message__c": {},
                    "Status__c": "0"
                }
            }
        }
    ]
}

我想将其转换为以下结构:

{
"batchRequests": [
    {
        "method": "PATCH",
        "url": "url",
        "richInput": {
            "Error_Message__c": "",
            "Status__c": "0"
        }
    },
    {
        "method": "PATCH",
        "url": "url",
        "richInput": {
            "Error_Message__c": "",
            "Status__c": "1"
        }
    }
]
}

如果可以通过javascript进行转换,请帮助我吗?

3 个答案:

答案 0 :(得分:2)

您可以使用这一行来完成。

 yourObject = { batchRequests: yourObject.root.batchRequests.map((x) => x.element) }

在这里尝试。

var yourObject = {
  "root": {
    "batchRequests": [{
        "element": {
          "method": "PATCH",
          "url": "url",
          "richInput": {
            "Error_Message__c": {},
            "Status__c": "0"
          }
        }
      },
      {
        "element": {
          "method": "PATCH",
          "url": "url",
          "richInput": {
            "Error_Message__c": {},
            "Status__c": "0"
          }
        }
      }
    ]
  }
}

yourObject = { batchRequests: yourObject.root.batchRequests.map((x) => x.element) }

console.log(yourObject);

答案 1 :(得分:0)

如果您的json项目称为json

let result = {batchRequests:[]};
for(let item of json.root.batchRequests){
    result.batchRequests.push(item.element);
}

答案 2 :(得分:0)

  1. 使用batchRequests函数解析map

    const batchRequests = data1.root.batchRequests.map(el => el.element)

  2. 使用此数据创建新对象:

    const data2 = { batchRequests }

const data1 = {
  "root": {
    "batchRequests": [
        {
            "element": {
                "method": "PATCH",
                "url": "url",
                "richInput": {
                    "Error_Message__c": {},
                    "Status__c": "0"
                }
            }
        },
        {
            "element": {
                "method": "PATCH",
                "url": "url",
                "richInput": {
                    "Error_Message__c": {},
                    "Status__c": "0"
                }
            }
        }
    ]
  }
}

const batchRequests = data1.root.batchRequests.map(el => el.element)

const data2 = { batchRequests }
console.log(data2)