Issue
i am having trouble combining objects from an array of Objects in typescript.
the Array looks like that:
0: {type: 'FeatureCollection', features: Array(134)}
1: {type: 'FeatureCollection', features: Array(109)}
what i need is an object (no array) with all "features" combined – so that it looks like this:
{type: 'FeatureCollection', features: Array(243)}
i am very new to typescript so sorry for that probably easy question…
Thank you so much!!
EDIT: maybe the question was not too good to understand. Hope this helps: Array(134) means there are 134 Objects inside. this does what i need manually when the array of objects (collection) is 2 long:
const result = [...collection[0].features, ...collection[1].features];
const resultCollection: FeatureCollection = collection[0];
resultCollection.features = result;
i need to make this work for any length of collection.
Solution
Are you looking for something like this? You’ll need to add types, but you can merge the features
arrays from all entries in the data
array using vanilla JS methods.
- Create the
output
object and specify itstype
. - Use
Array#filter
to select the entries indata
with the matching type. - Use
Array#flatMap
to select thefeatures
array from each of the entries above and project their contents into a single array.
const data = [
{ type: 'FeatureCollection', features: [1, 2, 3] },
{ type: 'FeatureCollection', features: [4, 5, 6] }
];
const output = {
type: 'FeatureCollection',
features: data
.filter(obj => obj.type === 'FeatureCollection')
.flatMap(obj => obj.features)
};
console.dir(output);
Answered By – D M
Answer Checked By – David Goodson (BugsFixing Volunteer)