How do I retain an entire geojson when attempting to sort and slice in React?

Viewed 111

I am attempting to sort a feature collection inside a geojson based off a property and then slice the first 5 features based on that geojson. With help from some people here I've got the basic sort and slice set up, but I noticed that when I return the final result from sorting and slicing my geojson, the final result is not a geojson but just the subset from the specific array inside the geojson.

How would I alter my code so that I retain the original geojson architecture but with only those top 5 sorted features? The purpose being to map the smaller sorted geojson result. I have a coded example here:

https://codesandbox.io/s/slicing-geojson-qg1hb?file=/src/App.js

With the "Original geojson" and "final result" printing in the console.

Here is what I am getting before and after the filter:

Before filter:

original geojson: 
{type: "FeatureCollection", features: Array(22), crs: Object}

After filter:

Final Result: 
(5) [Object, Object, Object, Object, Object]
0: Object
type: "Feature"
geometry: Object
properties: Object
1: Object
2: Object
3: Object
4: Object
​

I would like the final result to look the same as the original except sorted in descending order and keeping only the first 5 features.

1 Answers

Not sure if this is the question. If I understood you correctly you what the original geoJSON but replace the features array with your filtered one.

You can just create a copy of an object with the spread operator and override the feature array with your new array.

console.log("Final Result:", {
  ...this.state.geojson,
  features: rearrangedFeatures,
});
Related