Je souhaite afficher ces données dans un tableau par pays. J'ai d'abord sélectionné tous les pays répétés dans un seul tableau et je les ai filtrés. Ensuite, je mappe toutes les données pour montrer cela dans le tableau mais je ne sais pas comment séparer ces pays après la cartographie. Mon objectif dans ce cas devrait être:
... maintenant j'ai un nom de pays dans chaque rangée dont je ne veux pas Allemagne Munich pop Allemagne Berlin pop Allemagne Dortmund pop
Code:
import React from "react";
import "./styles.css";
import { data } from "./data";
export default function App() {
let countries = [];
const mapCountries = data.map((country, index) =>
countries.push(country.country)
);
countries = countries.filter(
(item, index, aref) => aref.indexOf(item) === index
);
const showCity = data.map((item, index) => (
<>
<tr>
<td colspan='2'>{item.country}</td>
</tr>
<tr>
<td>{item.city}</td>
<td>{item.pop}</td>
</tr>
</>
))
return (
<div className="App">
<table>
{showCity}
</table>
</div>
);
}
export const data = [
{
country: "Spain",
city: "Madrit",
pop: 3500000
},
{
country: "Spain",
city: "Barcelona",
pop: 1500000
},
{
country: "Spain",
city: "Valencia",
pop: 1000000
},
{
country: "Germany",
city: "Berlin",
pop: 4500000
},
{
country: "Germany",
city: "Munich",
pop: 1500000
},
{
country: "Germany",
city: "Dortmund",
pop: 1000000
},
{
country: "England",
city: "London",
pop: 8000000
},
{
country: "England",
city: "Liverpool",
pop: 500000
},
{
country: "England",
city: "Manchester",
pop: 1000000
}
];
4 Réponses :
Voici comment vous pouvez regrouper les données par pays:
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [nations, setNations] = useState(getNations(data));
const showCity = Object.keys(nations).map((item, index) => (
<>
<th>
<td colspan="2">{item}</td>
</th>
{nations[item]["city"].map((_, i) => (
<tr>{nations[item]["city"][i] + ":" + nations[item]["pop"][i]}</tr>
))}
</>
));
return (
<div className="App">
<table>{showCity}</table>
</div>
);
}
const data = [
{
country: "Spain",
city: "Madrit",
pop: 3500000
},
{
country: "Spain",
city: "Barcelona",
pop: 1500000
},
{
country: "Spain",
city: "Valencia",
pop: 1000000
},
{
country: "Germany",
city: "Berlin",
pop: 4500000
},
{
country: "Germany",
city: "Munich",
pop: 1500000
},
{
country: "Germany",
city: "Dortmund",
pop: 1000000
},
{
country: "England",
city: "London",
pop: 8000000
},
{
country: "England",
city: "Liverpool",
pop: 500000
},
{
country: "England",
city: "Manchester",
pop: 1000000
}
];
const getNations = () => {
let sol = {};
for (let country of data) {
if (sol[country.country] === undefined) {
sol[country.country] = { city: [country.city], pop: [country.pop] };
} else {
sol[country.country] = {
city: [...sol[country.country].city, country.city],
pop: [...sol[country.country].pop, country.pop]
};
}
}
return sol;
};
Exemple complet de ReactJS basé sur votre question:
const data = [
{
country: "Spain",
city: "Madrit",
pop: 3500000,
},
{
country: "Spain",
city: "Barcelona",
pop: 1500000,
},
{
country: "Spain",
city: "Valencia",
pop: 1000000,
},
{
country: "Germany",
city: "Berlin",
pop: 4500000,
},
{
country: "Germany",
city: "Munich",
pop: 1500000,
},
{
country: "Germany",
city: "Dortmund",
pop: 1000000,
},
{
country: "England",
city: "London",
pop: 8000000,
},
{
country: "England",
city: "Liverpool",
pop: 500000,
},
{
country: "England",
city: "Manchester",
pop: 1000000,
},
];
let sol = {};
for (let country of data) {
if (sol[country.country] === undefined) {
sol[country.country] = { city: [country.city], pop: [country.pop] };
} else {
sol[country.country] = {
city: [...sol[country.country].city, country.city],
pop: [...sol[country.country].pop, country.pop],
};
}
}
//console.log(sol);
for (let key of Object.keys(sol)) {
console.log(key);
for (let i in sol[key].city) {
console.log(sol[key].city[i], " ", sol[key].pop[i]);
}
console.log("------------");
}Capture d'écran:
Exemple de travail: Codesandbox
Comme vous avez une valeur de toutes les nations et de leurs villes regroupées, vous pouvez effectuer un filtrage si nécessaire très facilement.
Lors du regroupement de données, j'essaie généralement d'utiliser la méthode de reduce . Cela peut être un peu intimidant à apprendre, mais il est très polyvalent une fois que vous vous y êtes habitué.
La fonction itérateur prend quatre paramètres; un accumulateur, la valeur actuelle, l'index actuel et le tableau source d'origine. Pour regrouper les données, nous n'avons généralement besoin que des deux premiers. Pour chaque élément, la fonction est appelée et la valeur de retour est transmise à l'itération suivante pour la valeur cumulée finale.
Le concept est de regrouper par un index spécifique, de préférence un identifiant (comme le nom du pays).
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
const data = [
{
country: "Spain",
city: "Barcelona",
pop: 1500000
},
{
country: "Spain",
city: "Valencia",
pop: 1000000
},
{
country: "Germany",
city: "Berlin",
pop: 4500000
},
];
class App extends React.Component {
render() {
const grouped = data.reduce((acc, item) => ({
// we use the spread operator to add all previous keys
...acc,
// Object.hasOwnProperty checks if the grouping key is present on acc
[item.country]: Object.hasOwnProperty.call(acc, item.country)
// if it is we use the existing group and add our item to its list
? [...acc[item.country], item]
// otherwise create a new array with the groups first item
: [item]
}),
// this is the initial value for acc, an empty object
{});
// Now the data looks something like
// {
// "Spain": [{ country: "Spain", city: "Barcelona", pop: 1500000 }],
// "Germany": [...]
// }
// With each country having an array of each item in it.
// In order to show this in a table you can first iterate each entry
// in grouped and for each group iterate each city.
const showCity = Object
.entries(grouped)
// we can use the destructuring operator to "unpack" country and its list of cities here
.map(([country, cities]) => (
<tbody>
<tr>
<td colSpan="2">
<span>{country}</span>
</td>
</tr>
{cities.map(city => (
<tr>
<td>{city.city}</td>
<td>{city.pop}</td>
</tr>
))}
</tbody>));
return (
<table>
{showCity}
</table>
);
}
}
ReactDOM.render(
<App />,
document.body
);La solution la plus simple consiste à créer une carte des villes de comté et à l'utiliser quand même lors du prochain traitement:
const data = [
{
country: "Spain",
city: "Madrit",
pop: 3500000
},
{
country: "Spain",
city: "Barcelona",
pop: 1500000
},
{
country: "Spain",
city: "Valencia",
pop: 1000000
},
{
country: "Germany",
city: "Berlin",
pop: 4500000
},
{
country: "Germany",
city: "Munich",
pop: 1500000
},
{
country: "Germany",
city: "Dortmund",
pop: 1000000
},
{
country: "England",
city: "London",
pop: 8000000
},
{
country: "England",
city: "Liverpool",
pop: 500000
},
{
country: "England",
city: "Manchester",
pop: 1000000
}
];
const createCountryCitiesMap = data => {
let countries = new Set();
data.map(item => countries.add(item.country));
let result = new Map();
countries.forEach(country =>
result.set(
country,
data.filter(item => item.country === country).map(item => ({...{}, ...{city: item.city, pop: item.pop}}))
)
);
return result;
};
createCountryCitiesMap(data).forEach((value, key) => console.log(key + JSON.stringify(value)));Vous pouvez utiliser grouper les pays avec Array.prototype.reduce() puis utiliser Object.entries() comme ceci:
const showCity = groupCountries.map(([country, cities], index) => (
<tbody key={new Date().getTime() + index}>
<tr>
<td colSpan="2">{country}</td>
</tr>
{cities.map(({ city, pop }) => (
<tr key={city}>
<>
<td>{city}</td>
<td>{pop}</td>
</>
</tr>
))}
</tbody>
));
puis le restituer comme ceci:
const groupCountries = Object.entries(
data.reduce((acc, { country, ...rest }) => {
if (!acc[country]) {
acc[country] = [rest];
} else {
acc[country] = [...acc[country], rest];
}
return acc;
}, {})
);
Voici le lien du bac à sable:
https://codesandbox.io/s/quirky-https-74ynq?fontsize=14&hidenavigation=1&theme=dark