我对这个json /数组很新,下面的数据来自一个表,我需要将它移植到另一个表,这需要我根据id最高的国家进行排序... 装载的国家是动态的...... 感谢有人能告诉我如何将所有国家分组到#34;国家"并推送到正确的数据[i]
var data = [
{"Product": "DESKTOP", "Type": "APPLE" , "CN": "", "IN": "", "SG": "20"},
{"Product": "DESKTOP", "Type": "DELL" , "CN": "", "IN": "", "SG": "20"},
{"Product": "LAPTOP", "Type": "XXX", "CN": "", "IN": "90", "SG": "28"},
{"Product": "MOBILE", "Type": "XXX","CN": "1","IN": "","SG": "28"},
{"Product": "TABLET", "Type": "XXX","CN": "13","IN": "","SG": "238"}
]
what_i_need = [
{"Product": "DESKTOP",
"Type": "APPLE",
"Country": [
{"country": "CN", "id": ""}
{"country": "IN", "id": ""}
{"country": "SG", "id": "20"}
]},
...
...
]
我试着做循环,但结果就像这样
[{"country": "CN", "id": ""}
{"country": "IN", "id": ""}
{"country": "SG", "id": "20"}
{"country": "CN", "id": ""}
{"country": "IN", "id": ""}
{"country": "SG", "id": "20"}
答案 0 :(得分:1)
您可以使用map
功能更改数组格式。
var data = [{
"Product": "DESKTOP",
"Type": "APPLE",
"CN": "",
"IN": "",
"SG": "20"
},
{
"Product": "DESKTOP",
"Type": "DELL",
"CN": "",
"IN": "",
"SG": "20"
},
{
"Product": "LAPTOP",
"Type": "XXX",
"CN": "",
"IN": "90",
"SG": "28"
},
{
"Product": "MOBILE",
"Type": "XXX",
"CN": "1",
"IN": "",
"SG": "28"
},
{
"Product": "TABLET",
"Type": "XXX",
"CN": "13",
"IN": "",
"SG": "238"
}
];
var fixedKeys = ["Product", "Type"];
var result = data.map(function(item) {
var x = {
Product: item.Product,
Type: item.Type,
Country: []
};
for (var country in item) {
if (item.hasOwnProperty(country) && !fixedKeys.includes(country))
x.Country.push({
country: country,
id: item[country]
});
}
return x;
});
console.log(result);

答案 1 :(得分:0)
您可以使用解决方案https://jsfiddle.net/sdhaojsp/
var data = [
{"Product": "DESKTOP", "Type": "APPLE" , "CN": "", "IN": "", "SG": "20"},
{"Product": "DESKTOP", "Type": "DELL" , "CN": "", "IN": "", "SG": "20"},
{"Product": "LAPTOP", "Type": "XXX", "CN": "", "IN": "90", "SG": "28"},
{"Product": "MOBILE", "Type": "XXX","CN": "1","IN": "","SG": "28"},
{"Product": "TABLET", "Type": "XXX","CN": "13","IN": "","SG": "238"}
];
var outputData = [];
$.each(data, function(i){
var temp = {};
var tempCountry = {};
$.each(data[i], function(key){
if(key === "Product" || key === "Type"){
temp[key] = data[i][key];
}else{
tempCountry["country"] = key;
tempCountry["id"] = data[i][key];
if(typeof temp["Country"] === 'undefined') {
temp["Country"] = [];
}
temp["Country"].push(tempCountry);
tempCountry = {};
}
});
outputData.push(temp);
});
console.log(outputData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>