我想更改json结构,该怎么办?
我得到一个看起来像这样的json:
data = [
{
"fyyear": "2019-2020",
"kraid": 5,
"kraname": "CSAT",
"kracriteria": 18,
"lowerlimit": 2,
"upperlimit": 3.99,
"startrange": 50,
"endrange": 60
},
{
"fyyear": "2019-2020",
"kraid": 5,
"kraname": "CSAT",
"kracriteria": 18,
"lowerlimit": 2,
"upperlimit": 3.99,
"startrange": 50,
"endrange": 60
}
]
但是我需要这种结构:
data = [{
"fyyear": "2020-2021",
"kraid": null,
"kraname": "",
"kracriteria": [
{
"lowerlimit": "QWER",
"upperlimit": "QWER",
"startrange": "QWERT",
"endrange": "QWERT"
},
{
"lowerlimit": "QWER",
"upperlimit": "QWERT",
"startrange": "QWER",
"endrange": "QWERT"
},
{
"lowerlimit": "QWERT",
"upperlimit": "QWERT",
"startrange": "QWERT",
"endrange": "QWERT"
}
]
答案 0 :(得分:0)
这是一个故意冗长的解决方案,可能会有所帮助,因为您似乎正在学习有关JavaScript对象和数组的一些基础知识。
(使用Array.prototype.map
可以更简洁地完成此操作)
const
data = getOriginalData(),
firstItem = data[0],
// Creates a resultArray containing a single (currently empty) resultObject
resultObject = {},
resultArray = [resultObject],
// Specifies the three kinds of properties for the result object
propsToCopyFromFirstItem = ["fyyear", "kraid", "kraname"],
arrayProp = "kracriteria",
childProps = ["lowerlimit", "upperlimit", "startrange", "endrange"];
// Loops through propsToCopyFromFirstItem:
// Looks in the first item of `data` for the value to use and
// creates a property with that name and value in the result object
for (let propName of propsToCopyFromFirstItem){
let valueForProp = firstItem[propName];
resultObject[propName] = valueForProp;
}
// Creates a property whose value is an empty array to add items to
// Loops through `data`:
// Makes an empty `nextItem` obj (to add to the arrayProp in resultObject)
// Loops through `childProps`:
// Looks in the currentProperty in the currentObject of `data` for the value
// Makes a new prop in nextItem with that name and value
resultObject[arrayProp] = [];
for (let currentObject of data){
const nextItem = {};
for (let currentPropName of childProps){
let valueForProp = currentObject[currentPropName];
nextItem[currentPropName] = valueForProp;
}
// Adds `nextItem` to the array property in resultObject
resultObject[arrayProp].push(nextItem);
}
// Logs the result (`resultObject` was added to `resultArray` before)
console.log(resultArray);
// Provides the original `data` array
function getOriginalData(){
return [
{
"fyyear": "2019-2020",
"kraid": 5,
"kraname": "CSAT",
"kracriteria": 18,
"lowerlimit": 2,
"upperlimit": 3.99,
"startrange": 50,
"endrange": 60
},
{
"fyyear": "2019-2020",
"kraid": 5,
"kraname": "CSAT",
"kracriteria": 18,
"lowerlimit": 3,
"upperlimit": 5.99,
"startrange": 70,
"endrange": 80
}
];
}