Creating a TypeScript function that adds or replaces an element in an array of objects

I am looking to create a function that accepts an array of objects, one object, and a key as input. The goal is for the function to return an array of objects with the new object at position 0 if it is not already in the array, or in the same position if it is. The key provided will be used to compare the objects, and can only be either a string or a number.

I have already written a function for this purpose, but it is important to note that each object must have an "id" property included.

export function addOrReplaceById<T extends Array<{ id: string }>>(
  arrayOfObjects: T,
  newObject: { id: string }
): T {
  const index = arrayOfObjects.findIndex((object) => object.id === newObject.id);

  if (index === -1) {
    arrayOfObjects.unshift(newObject);
  } else {
    arrayOfObjects[index] = newObject;
  }

  return arrayOfObjects;
}

Answer №1

If you want to create a function that adds or replaces an object in an array based on a specified key, you can follow this approach:

export function addOrReplaceObjectByKey<T extends {[property: string]: any}>(
    objectsArray: T[],
    newObject: T,
    keyToCheck: keyof T,
): T[] {
    const index = objectsArray.findIndex((obj) => obj[keyToCheck] === newObject[keyToCheck]);

    if (index === -1) {
        objectsArray.unshift(newObject);
    } else {
        objectsArray[index] = newObject;
    }
    return objectsArray;
};

Answer №2

Take a look at this scenario:

export function addOrReplaceById<
    Obj extends { id: string },
    Arr extends Array<Obj>
>(
    arrayOfObjects: [...Arr],
    newObject: Obj
) {
    const data = arrayOfObjects
        .reduce<{ exists: boolean, arr: Obj[] }>(
            (acc, obj) =>
                obj.id === newObject.id ? {
                    ...acc,
                    exists: true,
                    arr: [...acc.arr, newObject]
                } : acc, {
            exists: false,
            arr: []
        });

    return data.exists ? data.arr : [newObject, ...data.arr]
}

The example above simplifies the complexity by avoiding the expensive operation of unshift. Instead, I introduced a new data structure {exists: boolean, arr:Obj[]}.

In addition, I made sure to return a new array rather than mutating the existing one.

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

Is there a way to transform a stringified array into an array in JavaScript if I do not have access to the original string?

Recently, I encountered a challenge where I had an array of items enclosed within "", and not '' (if that distinction matters): "['item 1', 'item2', 'item 3']" I am interested in converting it to ...

Why isn't the pipe working when trying to extract the last 2 characters using

I am currently working on creating a regex pattern to extract the variables passed to a JavaScript constructor. The format of the input data will always be similar to this: app.use(express.static('public')); The regex I have devised to remove ...

Tips for effectively showcasing JSON in an Angular directive

I am facing an issue with my Angular app that utilizes ui-router. I have set up a service and directive, but I am unable to display JSON data. Surprisingly, it works perfectly fine without the directive when I directly display it in the main template (home ...

How can we transform words with double "OO" in a paragraph into green squares using React? For instance, changing "clooney" to "cl[green square]ey"

import React, { Component } from 'react'; class App extends Component { constructor() { super(); this.state = { modifiedPar: "", newPar: "modified paragraph will be displayed here"}; } greenSquareMaker = word = ...

Is JavaScript Promise Chaining Allowed?

I have a question regarding my code, despite it currently functioning correctly. Specifically, I'm wondering if the sequence of promises in my database is valid. Promise 1 must be fulfilled before moving on to Promise 2 because I rely on the data and ...

Angular 2: Enhancing the table with Bootstrap Modal behind the scenes

I have a roster of students that I can manipulate using CRUD functions. Each student entry has an Edit button <table class="table table-bordered table-striped"> <thead class="studentHeader"> <tr> <td>Roll Number</t ...

Troubleshooting [object Object] Error in Node.js using Express

This is my Unique Code handleLoginRequest(req, res, next) { try { const {username, password} = req.body; const user = await UserModel.findOne({username}); if(!user) throw {status: 401, message:'Invalid username or password' ...

Having trouble accessing the input class with jQuery

When I click the "Reset To Default Settings" button in my form, I want to clear the default colors in my 4 color pickers. Each of them has an input type text field with the class anyicon-form-colorpicker. To achieve this, I locate the <a> tag and use ...

Generating Ionic components with HTML markup

When I use $http.get to fetch a JSON file, the Ionic view is not displaying the output correctly: loadNews() { return new Promise(resolve => { let header = {"Content-Type": "application/json"}; this.http.get('http://www.mywebs ...

What is the optimal method for creating direct duplicates of string variables in C#?

Imagine having an array of strings resulting from the execution of the Split method string[] parsed = message.Split(' '); Then, a specific value from this array needs to be stored in a new string string name = parsed[3]; Subsequently, removin ...

Will not pass over if the number is already in the array?

Currently, I am developing a method to determine how many times a specific number appears in an array. Here is my method: public void freq(int[] arr) { Arrays.sort(arr); String output = ""; int count = 0; for (int i = 0; i ...

No content in webpack result file when using express and react

Trying to implement webpack into the basic react comment list tutorial has been a bit of a challenge for me. Everything seems to be functioning properly, but my output file never actually contains any content. Let's take a look at my webpack configur ...

Currently, I am experiencing difficulties with two specific aspects of the website I am working on - the hamburger menu and the slideshow feature

I'm having trouble with the menu on my website. It's not functioning as expected - the dropdown feature isn't working, and two items are not staying in the correct position under the parent ul despite attempts to position them using CSS. Add ...

Don't forget to keep in mind the importance of the "Radio" value when you are submitting a form to yourself on

When dealing with a text input, you can remember the value entered by the user if the form is submitted to itself. This technique comes in handy for tools like a picture upload tool, where the user's input needs to be saved to avoid retyping after upl ...

Trouble with 'this.function' and handling scope within my code

Hi there! I'm having an issue with this code snippet: Whenever I reach line 109, I encounter an error message that reads "TypeError: Result of expression 'this.allVarsDefined' [undefined] is not a function." I find scope in javascript to b ...

Exploring the intricacies of using jquery text() with HTML Entities

I am having difficulty grasping the intricacies of the jquery text() function when used with HTML Entities. It appears that the text() function converts special HTML Entities back to regular characters. I am particularly uncertain about the behavior of thi ...

improper rendering of highcharts

Receiving data in JSON format as shown below: <?php $monthlyParticipation='[{"project_title":"test project 44","project_ref_id":"113","amount":"13000.00","months":"Feb"},{"project_title":"sdsdsd","project_ref_id":"112","amount":"50000.00","months ...

Spinning a basic square two times

I am somewhat familiar with Blender 3D, but I have very little experience with 3D programming and I am currently trying to work with three.js. My query is this: I have a basic cube that I rotated around the y-axis; now I need to rotate it again around the ...

Error occurred while attempting to fetch the associated objects from the Parse.Query

I'm running into an issue with Parse.Query and how to handle the result promise. Here's my current code snippet: var ga = new Parse.Query(Game); ga.include('away_team'); ga.include('home_team'); ga.equalTo("objectId", req.par ...

Having trouble incorporating a react component I discovered into my application. Encountering an error message stating "Attempted import error."

My aim is to integrate an existing react component (shown below) that I came across on the internet into my application for use, specifically an animated navigation bar. Upon attempting to compile the code snippets below (snippets 2 and 3), I encountered ...