How to Merge Items within an Array of Objects Using Typescript?

I'm currently facing a challenge in combining objects from an array of Objects in typescript.

The structure of the array is as follows:

0: {type: 'FeatureCollection', features: Array(134)}
1: {type: 'FeatureCollection', features: Array(109)}

What I am looking for is to create a single object (not an array) with all "features" combined, like this:

{type: 'FeatureCollection', features: Array(243)}

As I am new to typescript, please excuse me if this seems like a basic question...

Thank you for your help!

EDIT: To clarify, when I mention Array(134), it means there are 134 objects inside. The manual approach for a collection of length 2 is shown below:

const result = [...collection[0].features, ...collection[1].features];
const resultCollection: FeatureCollection = collection[0];
resultCollection.features = result;

I need to generalize this solution to work for any length of collection.

Answer №1

Need help achieving a similar result? By incorporating types, you can combine the arrays of `features` from all elements within the `data` array using vanilla JavaScript methods.

  1. Initialize an `output` object and define its `type` property.
  2. Utilize Array#filter to filter out entries in `data` based on their type.
  3. Leverage Array#flatMap to extract the `features` arrays from these filtered entries and merge them into one 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);

Answer №2

To simplify the process, utilize the Array.prototype.reduce method along with the spread operator

const items = [
  { category: "apple", attributes: ["red", "juicy", "sweet"] },
  { category: "apple", attributes: ["sour", "crisp", "healthy"] },
];

const mergeAttributes = (items) => items.reduce((accumulator, current) => {
  accumulator.attributes = [...(accumulator.attributes ?? []), ...current.attributes];
  return accumulator;
}, { category: (items[0].category) });

console.log(mergeAttributes(items));

Answer №3

When using the reduce method :

const array = [
  {type: 'FeatureCollection', features: [1, 2, 3]},
  {type: 'FeatureCollection', features: [4, 5, 6]},
  {type: 'Test', features: [4, 5, 6]}
]

const merged = array.reduce((arr, item) => {
  const found = arr.find((i) => i.type === item.type);
  if (found) {
    found.features.push(...item.features);
  } else {
    arr.push(item);
  }
  return arr;
}, []);

console.log(merged);

---- MODIFIED ----

alternative approach :

const array = [
  {type: 'FeatureCollection', features: [1, 2, 3]},
  {type: 'FeatureCollection', features: [4, 5, 6]},
  {type: 'Test', features: [4, 5, 6]}
]

const merged = array.reduce((obj, item) => {
  if (obj[item.type]) {
    obj[item.type].push(...item.features);
  } else {
    obj[item.type] = item.features;
  }
  return obj;
}, {} as {[key: string]: number[]});

const keys = Object.keys(merged);
const result = keys.map((k) => ({type: k, features: merged[k]}));

console.log(result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generate listview items containing anchor tags automatically

I am currently developing a web application using Jquery Mobile. After retrieving data from a webservice function, I am utilizing an ajax call to display this data on my webpage. $('[data-role=page]').on('pageshow', function () { var u ...

Set a unique class for several elements depending on a given condition

Is there a way to assign a color class based on the element's value without looping through all elements? Check out my jsfiddle HTML <div> <ul> <li class="MyScore">90</li> <li class="MyScore"> ...

The minimum and maximum validation functions are triggered when I am not utilizing array controls, but they do not seem to work when I use array controls

Take a look at the stack blitz example where min and max validation is triggered: https://stackblitz.com/edit/angular-mat-form-field-icrmfw However, in the following stack blitz with an array of the same controls, the validation does not seem to be worki ...

"Elaborate" Typescript Conditional Generic Types

Scenario I am currently working on implementing strong typing for the onChange function of a UI library's Select component. To provide some context, the existing type definition for their onChange is as follows: onChange?: (...args: any[]) => v ...

When trying to bind an object that is constantly changing, one-way binding may not effectively capture those dynamic modifications

For a detailed review of the code, please check out the plnkr. I am quite new to AngularJS components. I have created two simple AngularJS components with the exact same bindings: bindings: { value:'@', field:'@', object: '<&a ...

The grouping of values in JavaScript is known as an array

I need assistance in modifying my code to generate dynamic buttons based on array elements instead of objects. Currently, the array I am using contains objects which is causing issues with tracking button status and other computations. Can you help me adju ...

Arranging numerous items based on date in JavaScript without prior knowledge

I'm facing an issue where I need to showcase JSON data containing events but want them sorted by time. The challenge is that the number of objects in the JSON can vary as users can keep adding more. Below is my code snippet demonstrating how the displ ...

Default modal overlay closure malfunctioning; encountering errors when manually managed through jQuery

A custom overlay has been designed and implemented. <div class="overlay modal" id="11"> <div class="background-overlay"></div> <div class="description"> <div class="hidden-xs"> <img src=' ...

What is the process for advancing to the next or previous step using Angular.js?

I am currently utilizing ui-route for routing purposes, specifically for navigating through a series of sequential forms. After submitting one form, I would like to automatically move on to the next step without hard coding the step name in the $state.go( ...

"Encountered npm error: JSON input ended unexpectedly" while trying to install express-mysql-session"

I'm currently developing a nodejs project that uses passportjs for user authentication and mysql as the database. I'm now looking to incorporate session storage by utilizing the ""express-mysql-session" package. However, when attemptin ...

"Trouble in Transmitting: Node.js Fails to

As a beginner in programming, I am currently following a tutorial to enhance my skills. I've encountered a roadblock and I can't seem to successfully post new entries using the code. I'm struggling to identify what I might be missing here. ...

Incomplete header data in Angular $resource GET request

Currently, I am working with Ionic 1.3 and Angular 1.5. My goal is to retrieve some header properties from my response. The code snippet I am using looks something like this: factory('Service', function($resource, API_SETTINGS, JsonData) { re ...

Maximizing Input Field Utility in React JS

I have a challenge with retrieving values from the input field and passing it to the useEffect. I specifically want the search to be triggered only after pressing the onSearch function. The issue is that I can only capture the value using the onChange func ...

Generating Angular2 CLI components with Angular-Meteor integration

Exploring Angular2 CLI and Meteor has been an interesting journey for me. One thing I've noticed is that when I create a component using Angular2 CLI, integrating it into another module is as simple as including it in the declarations array of that mo ...

Utilizing React Router V4 to Render Dual Components on a Single Route

Looking for help with these routes <Route exact path={`/admin/caters/:id`} component={Cater} /> <Route exact path={'/admin/caters/create'} component={CreateCater} /> After visiting the first route, I see a cater with an ID display ...

Controlling opacity with jQuery animate() function using a click event

I have a specific requirement for an animation. When the button is clicked, I need the element to transition from 0 opacity to full 1 opacity within 300 milliseconds. The issue I am facing is that when the button is clicked, the animation does not work a ...

Using jQuery to generate a JSON object dynamically based on the values entered in each input field

I'm facing a situation where I need to extract data from a JSON format using PHP. However, I'm struggling with how to structure the Javascript object in order to dynamically create the JSON format. Here is my current scenario: <input title=" ...

The <b-list-group-item> component in a Vue.js CLI application using bootstrap-vue is failing to render

My Vue-CLI app uses Bootstrap-vue and axios to fetch JSON data. The HTML code in my App.vue displays the data using UL and LI tags: <p v-if="loading">Loading...</p> <ul v-else> <li v-for="(value, key) in post" :key="key"> ...

Node.js npm-migration enables the creation of multiple tables in a single migration process

I am new to npm-migration for nodejs and I am exploring ways to streamline the process of creating multiple tables using a single migration, rather than having separate migrations for each table creation. I have experimented with the following code: "up": ...

How to show the raw image content-type using Vue.js

When retrieving an image from a REST API through an HTTP GET with a request body, I have successfully verified the returned content using node.js and chai.js: expect(res).to.have.header('Content-Type', 'image/jpeg'); expect ...