我有来自服务器端的JSON数据,但不是我想要的。我的json数据有多个循环,我想将其转换为单个循环。
我正在获取JSON
[
[
"Year",
"2018-9",
"2017-9"
],
[
"JAYANAGAR",
"2018-9",
857
],
[
"MALLESHWARAM",
"2018-9",
169
],
[
"KOLAR",
"2018-9",
178
],
[
"JAYANAGAR",
"2017-9",
635
],
[
"MALLESHWARAM",
"2017-9",
56
],
[
"KOLAR",
"2017-9",
90
]
]
在这里,例如jayanagar malleshwaram和kolar会重复我的不同约会
我正在尝试将其转换为类似的内容
[
[
"Year",
"2018-9",
"2017-9"
],
[
"Jayanagar",
857,
635
],
[
"Malleshwaram",
169,
56
],
[
"Kolar",
178,
90
]
]
在我的第一个json数据中,重复的日期是2018-8
和2017-8
我想映射数据并将其简化为想要获取的数据。
我知道可以使用JavaScript来完成,但是我不知道该怎么做。
答案 0 :(得分:3)
假设每个“位置”的数据按正确的顺序排列,则可以像这样使用reduce
和Object.values()
:
const input=[["Year","2018-9","2017-9"],["JAYANAGAR","2018-9",857],["MALLESHWARAM","2018-9",169],["KOLAR","2018-9",178],["JAYANAGAR","2017-9",635],["MALLESHWARAM","2017-9",56],["KOLAR","2017-9",90]]
const merged = input.reduce((acc, arr) => {
const [city, year, value] = arr;
if (city === "Year")
acc[city] = arr
else {
acc[city] = acc[city] || [city]
acc[city].push(value)
}
return acc;
}, {})
const output = Object.values(merged)
console.log(output)
答案 1 :(得分:0)
您可以将数据分组以创建所需的结构
const first = foo.shift();
const res = Array.from(
foo.reduce((a, [t,_,n]) => a.set(t, (a.get(t) || []).concat(n)), new Map)
).map(e => [].concat(...e));
res.unshift(first);
console.log(res);
<script>
const foo = [
[
'Year',
'2018-9',
'2017-9'
],
[
'JAYANAGAR',
'2018-9',
857
],
[
'MALLESHWARAM',
'2018-9',
169
],
[
'KOLAR',
'2018-9',
178
],
[
'JAYANAGAR',
'2017-9',
635
],
[
'MALLESHWARAM',
'2017-9',
56
],
[
'KOLAR',
'2017-9',
90
]
];
</script>
答案 2 :(得分:0)
const dataSet = [
[
"Year",
"2018-9",
"2017-9"
],
[
"JAYANAGAR",
"2018-9",
857
],
[
"MALLESHWARAM",
"2018-9",
169
],
[
"KOLAR",
"2018-9",
178
],
[
"JAYANAGAR",
"2017-9",
635
],
[
"MALLESHWARAM",
"2017-9",
56
],
[
"KOLAR",
"2017-9",
90
]
];
const dataBody = dataSet.slice(1);
const transformedDataBody = dataBody.reduce(function (currentValue, nextValue){
currentValue[nextValue[0]] = currentValue[nextValue[0]] || [nextValue[0]];
currentValue[nextValue[0]].push(nextValue[2]);
return currentValue;
}, {})
let finalDataSet = [ dataSet[0] ];
Object.keys(transformedDataBody).map(function(key){
finalDataSet.push(transformedDataBody[key]);
})
console.log(finalDataSet);
这就是你想要的吗?