这是我所拥有的结构,我已从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进行转换,请帮助我吗?
答案 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)
使用batchRequests
函数解析map
:
const batchRequests = data1.root.batchRequests.map(el => el.element)
使用此数据创建新对象:
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)