我有以下输入json有效负载,
{
"Products": {
"Product": [
{
"ProductID": 458761,
"Designation": "CB 024-2001",
"EntryDate": "2002-01-20T19:00:00.000-05:00",
"S1": "024",
"S2": 2001,
"Year": 2001
},
{
"ProductID": 458234,
"Designation": "AGRS03/08",
"EntryDate": "2008-03-05T19:00:00.000-05:00",
"S1": "03",
"S2": "08",
"Year": 2008
}
]
}
}
现在我需要将其转换为以下JSON格式。
[
{
"Designation": "CB 024-2001",
"EntryDate": "2002-01-20T19:00:00.000-05:00",
"ProductID": 458761,
"S1": "024",
"S2": 2001,
"Year": 2001
},
{
"Designation": "AGRS03/08",
"EntryDate": "2008-03-05T19:00:00.000-05:00",
"ProductID": 458761,
"S1": "03",
"S2": "08",
"Year": 2008
}
]
有人可以帮我编写一个JavaScript来完成这项任务。任何帮助都非常感谢。
答案 0 :(得分:3)
假设您的原始json存储在名为input
的变量中。这可以使用以下代码完成:
var output = input.Products.Product;
ORIGINAL:您可以使用map
:
var output = input.Products.Product.map(function(inObj) {
return {
"Designation": inObj.Designation,
"EntryDate": inObj.EntryDate,
"S1": inObj.S1,
"S2": inObj.S2,
"Year": inObj.Year
}
});
这将为您提供所需的输出 - 一组对象,并删除了ProductID。在处理对象引用时,我有点生疏,但您可以使用delete
来缩短它:
var output = input.Products.Product.map(function(inObj) {
var outObj = inObj;
delete outObj.ProductID;
return outObj;
});
这也会改变原来的input
值,因此除非您不打算再次使用该数据,否则我不会推荐它。
答案 1 :(得分:3)
var first = {
"Products": {
"Product": [
{
"ProductID": 458761,
"Designation": "CB 024-2001",
"EntryDate": "2002-01-20T19:00:00.000-05:00",
"S1": "024",
"S2": 2001,
"Year": 2001
},
{
"ProductID": 458234,
"Designation": "AGRS03/08",
"EntryDate": "2008-03-05T19:00:00.000-05:00",
"S1": "03",
"S2": "08",
"Year": 2008
}
]
}
}
然后:
var second = first.Products.Product;
使其完全符合您的要求:
for(var i = 0; i<second.length; i++){
delete second[i].ProductID;
}
答案 2 :(得分:1)
你可以使用这个小功能:
var a = {
"Products": {
"Product": [{
"ProductID": 458761,
"Designation": "CB 024-2001",
"EntryDate": "2002-01-20T19:00:00.000-05:00",
"S1": "024",
"S2": 2001,
"Year": 2001
}, {
"ProductID": 458234,
"Designation": "AGRS03/08",
"EntryDate": "2008-03-05T19:00:00.000-05:00",
"S1": "03",
"S2": "08",
"Year": 2008
}]
}
};
function newJSON(array){
var b = array.Products.Product;
b.forEach(function(e){delete e.ProductID});
return JSON.stringify(b);
}
document.write(newJSON(a));
&#13;
答案 3 :(得分:0)
使用下划线:
var result = _.map(data.Products.Products, (product) => {
return _.omit(product, 'ProductID');
});