Я получаю данные из Backend, которые приведены ниже. и должны манипулировать данными в соответствии с требованием. как преобразовать следующий формат массива JSON в соответствии с требованиями ReactJS. данные Json, приведенные ниже
[
{
"date": "2020-12-10",
"airline": "Air asia",
"totalprice": 4180,
"departuretime": "20:25"
},
{
"date": "2020-12-10",
"airline": "Air asia",
"totalprice": 4180,
"departuretime": "11:25"
},
{
"date": "2020-12-10",
"airline": "Air asia",
"totalprice": 4180,
"departuretime": "22:45"
},
{
"date": "2020-12-10",
"airline": "Air india",
"totalprice": 4180,
"departuretime": "06:10",
},
{
"date": "2020-12-10",
"airline": "Air india",
"totalprice": 4180,
"departuretime": "13:50",
},
{
"date": "2020-12-10",
"airline": "Air india",
"totalprice": 4180,
"departuretime": "07:05",
}
]
преобразовать вышеуказанные данные в соответствии со следующими данными
[
{
"airline": "Air asia",
"data": [
{
"date": "2020-12-10",
"totalprice": 5180,
"departuretime": "20:25"
},
{
"date": "2020-12-10",
"totalprice": 4180,
"departuretime": "11:25"
},
{
"date": "2020-12-10",
"totalprice": 4180,
"departuretime": "22:45"
}
]
},
{
"airline": "Air india",
"data": [
{
"date": "2020-12-10",
"totalprice": 4180,
"departuretime": "06:10"
},
{
"date": "2020-12-10",
"totalprice": 4180,
"departuretime": "13:50"
},
{
"date": "2020-12-10",
"totalprice": 4180,
"departuretime": "07:05"
}
]
}
]
Как преобразовать методом Javascript?
let data = [
{
"date": "2020-12-10",
"airline": "Air asia",
"totalprice": 4180,
"departuretime": "20:25"
},
{
"date": "2020-12-10",
"airline": "Air asia",
"totalprice": 4180,
"departuretime": "11:25"
},
{
"date": "2020-12-10",
"airline": "Air asia",
"totalprice": 4180,
"departuretime": "22:45"
},
{
"date": "2020-12-10",
"airline": "Air india",
"totalprice": 4180,
"departuretime": "06:10",
},
{
"date": "2020-12-10",
"airline": "Air india",
"totalprice": 4180,
"departuretime": "13:50",
},
{
"date": "2020-12-10",
"airline": "Air india",
"totalprice": 4180,
"departuretime": "07:05",
}
]
// use can use this object as it is too.
let sol = {}
data.forEach(d => {
if (sol[d.airline]){
sol[d.airline].data.push({"date": d.date, "totalprice": d.totalprice, "departuretime": d.departuretime})
}else{
sol[d.airline] = {"data" : [{"date": d.date, "totalprice": d.totalprice, "departuretime": d.departuretime}]}
}
})
let d = Object.keys(sol).map(key => {
return {"airline": key, "data": sol[key]["data"]}
})
console.info(d)
Вы можете использовать функцию сокращения, чтобы решить эту проблему. См. ниже:
const airlinesReducer = (accumulator, current) => {
// Breakdown the entry into name and other fields
let { airline, ...airlineFields} = current;
// Look for a previously indexed entry
let airlineData = accumulator.indexed[airline]
// If the airline hasn't been indexed before, add it to the index map
if (!airlineData) {
// Create a reference for the new array to be filled
airlineData = accumulator.indexed[airline] = []
accumulator.result.push({
airline: current.airline,
data: airlineData
})
}
// Push this entry to the results array
airlineData.push(airlineFields)
return accumulator
}
let result = array.reduce(airlinesReducer, { indexed: {}, result: [] }).result
Почему это перебор?
Случайно есть твит... twitter.com/dan_abramov/status/1338253118199508992
const input = [{"date":"2020-12-10","airline":"Air asia","totalprice":4180,"departuretime":"20:25"},{"date":"2020-12-10","airline":"Air asia","totalprice":4180,"departuretime":"11:25"},{"date":"2020-12-10","airline":"Air asia","totalprice":4180,"departuretime":"22:45"},{"date":"2020-12-10","airline":"Air india","totalprice":4180,"departuretime":"06:10"},{"date":"2020-12-10","airline":"Air india","totalprice":4180,"departuretime":"13:50"},{"date":"2020-12-10","airline":"Air india","totalprice":4180,"departuretime":"07:05"}];
// Group data...
const groups = {};
input.forEach(({
airline,
...rest
}) => (groups[airline] = groups[airline] || []).push(rest));
// ... and transform back to array.
const output = Object.entries(groups).map(([airline, data]) => ({
airline,
data
}));
console.info(output);
Вот еще одно решение с некоторым кодом ES6
const arr = [
{
date: '2020-12-10',
airline: 'Air asia',
totalprice: 4180,
departuretime: '20:25',
},
{
date: '2020-12-10',
airline: 'Air asia',
totalprice: 4180,
departuretime: '11:25',
},
{
date: '2020-12-10',
airline: 'Air asia',
totalprice: 4180,
departuretime: '22:45',
},
{
date: '2020-12-10',
airline: 'Air india',
totalprice: 4180,
departuretime: '06:10',
},
{
date: '2020-12-10',
airline: 'Air india',
totalprice: 4180,
departuretime: '13:50',
},
{
date: '2020-12-10',
airline: 'Air india',
totalprice: 4180,
departuretime: '07:05',
},
];
//Using a Set datastructure to capture individual airline names
let uniqueAirlinesSet = new Set();
for (let el of arr) {
uniqueAirlinesSet.add(el.airline);
}
// Converted set to array of unique elements like this["Air Asia","Air India"]
const uniqueAirlinesArr = [...uniqueAirlinesSet];
const newFormattedArray = uniqueAirlinesArr.reduce((acc, el) => {
const obj = {
airline: el,
data: [],
};
for (let { airline, date, departuretime, totalprice } of arr) {
if (el === airline) {
obj.data.push({ date, departuretime, totalprice });
}
}
acc.push(obj);
return acc;
}, []);
Что вы пробовали? Вы пробовали читать методы массива?