根据键读取并以 JSON 格式在 JavaScript 中解析
假设我们有一个类似这样的 JSON 数组 −
const arr = [{
"data": [
{ "W": 1, "A1": "123" },
{ "W": 1, "A1": "456" },
{ "W": 2, "A1": "4578" },
{ "W": 2, "A1": "2423" },
{ "W": 2, "A1": "2432" },
{ "W": 2, "A1": "24324" }
]
}];我们需要编写一个 JavaScript 函数,该函数接受这样一个数组并将其转换为以下 JSON 数组 −
[
{
"1": [
{
"A1": "123"
},
{
"A1": "456"
}
]
},
{
"2": [
{
"A1": "4578"
},
{
"A1": "2423"
},
{
"A1": "2432"
},
{
"A1": "24324"
}
]
}
];示例
const arr = [{
"data": [
{ "W": 1, "A1": "123" },
{ "W": 1, "A1": "456" },
{ "W": 2, "A1": "4578" },
{ "W": 2, "A1": "2423" },
{ "W": 2, "A1": "2432" },
{ "W": 2, "A1": "24324" }
]
}];
const groupJSON = (arr = []) => {
const preCombined = arr[0].data.reduce((acc, val) => {
acc[val.W] = acc[val.W] || [];
acc[val.W].push({ A1: val.A1 });
return acc;
}, {});
const combined = Object.keys(preCombined).reduce((acc, val) => {
const temp = {};
temp[val] = preCombined[val];
acc.push(temp);
return acc;
}, []);
return combined;
};
console.log(JSON.stringify(groupJSON(arr), undefined, 4));输出
控制台中的输出将是 −
[
{
"1": [
{
"A1": "123"
},
{
"A1": "456"
}
]
},
{
"2": [
{
"A1": "4578"
},
{
"A1": "2423"
},
{
"A1": "2432"
},
{
"A1": "24324"
}
]
}
]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP