解析嵌套的JSON数组Object nodejs

时间:2017-10-27 12:50:05

标签: javascript arrays json node.js object

我正在尝试解析JSON对象并删除Key' id'在其中,我能够删除' id'它出现在对象的根目录中,但无法在嵌套的数组对象中进行遍历,这些对象也具有' id'键并删除它们,现在遵循代码块

var json = {
"id" : "a28b469b-b4f2-4846-9b5f-9d866f249bbe",
"description" : "Cost of Product",
"periodicity" : "calendar-monthly",
"Vanilla" : [ {
  "id" : "22382c50-f56f-40b7-a308-203da052c5bc",
  "price" : {
    "amount" : 100.000,
    "currency" : "USD"
  },
  "packing" : "RECURRING",
  "billedInAdvance" : true
} ],
"Chocolate" : [ {
  "id" : "44672921-1966-456e-bde2-87ef72f31cab",
  "price" : {
    "amount" : 256.000000,
    "currency" : "USD"
  },
  "packing" : "Box_Usage"
} ],
"Peach" : [ {
  "id" : "e3a600e2-a2ed-4872-8e6d-5d59ec5ca02d",
  "packing" : "Box_Usage",
  "diff" : [ {
    "pricePerUnit" : {
      "amount" : 25.000000,
      "currency" : "USD"
    },
    "fixedPrice" : {
      "amount" : 36.000000,
      "currency" : "USD"
    }
  } ]
} ],
"Strawberry" : [ {
  "id" : "43b4a121-455a-4828-b4bf-1bacda49f9ce",
  "packing" : "Box_Usage",
  "diff" : [ {
    "pricePerUnit" : {
      "amount" : 100.000000,
      "currency" : "USD"
    }
  } ]
} ]

}

我可以删除' id'通过索引访问数组对象中的属性,但是当JSON中的键增长时,这不会处理动态方案。任何建议都是有价值的

1 个答案:

答案 0 :(得分:1)

你可以递归地执行:每次在对象中找到一个数组时,你都会遍历它以删除每个元素中的id。



var json = {
"id" : "a28b469b-b4f2-4846-9b5f-9d866f249bbe",
"description" : "Cost of Product",
"periodicity" : "calendar-monthly",
"Vanilla" : [ {
  "id" : "22382c50-f56f-40b7-a308-203da052c5bc",
  "price" : {
    "amount" : 100.000,
    "currency" : "USD"
  },
  "packing" : "RECURRING",
  "billedInAdvance" : true
} ],
"Chocolate" : [ {
  "id" : "44672921-1966-456e-bde2-87ef72f31cab",
  "price" : {
    "amount" : 256.000000,
    "currency" : "USD"
  },
  "packing" : "Box_Usage"
} ],
"Peach" : [ {
  "id" : "e3a600e2-a2ed-4872-8e6d-5d59ec5ca02d",
  "packing" : "Box_Usage",
  "diff" : [ {
    "pricePerUnit" : {
      "amount" : 25.000000,
      "currency" : "USD"
    },
    "fixedPrice" : {
      "amount" : 36.000000,
      "currency" : "USD"
    }
  } ]
} ],
"Strawberry" : [ {
  "id" : "43b4a121-455a-4828-b4bf-1bacda49f9ce",
  "packing" : "Box_Usage",
  "diff" : [ {
    "pricePerUnit" : {
      "amount" : 100.000000,
      "currency" : "USD"
    }
  } ]
} ]
};
function removeId(obj) {
    delete obj.id;
    Object.keys(obj).forEach(key => {
        if (Array.isArray(obj[key])) {
            obj[key].forEach(o => {
                removeId(o);
            });
        } 	
    });
}
removeId(json);
console.log(json);