In JavaScript, you can add or replace an object in an array of objects by checking for a specific property

I am looking for a more concise way to add or replace an object within an array.

var arr = [
  {uid: 1, name: "bla", description: "cucu"},
  {uid: 2, name: "smth else", description: "cucarecu"},
]

Here is a new object:

var mynewObject = {uid: 1, name: "newBlabla", description: "newDesc"};

Currently, I am using the following function to achieve this:

function addOrReplace (arr, object) {
  var index = arr.findIndex(x => object.uid === x.uid);
  if (-1 === index) {
    arr.push(object);
  } else {
    arr[index] = object;
  }
  return arr;
} 

However, I find this method somewhat cumbersome. Is there a more elegant way to accomplish this in just one or two lines?

The original array must remain intact and the new object should only be checked by its uid property.

Answer №1

To simplify the code and achieve the same functionality in a more concise manner, you can use Array#findIndex method by assigning its result to the unused parameter idx of the function. This will allow you to overwrite its default value (which is undefined) or the value with which the function was originally called. Then utilize a ternary operator to either modify the existing object or add it to the array, before finally returning the updated array.

const arr1 = [
  { uid: 1, name: "bla", description: "cucu" },
  { uid: 2, name: "smth else", description: "cucarecu" },
]
const mynewObject1 = { uid: 1, name: "newBlabla", description: "newDesc" };

const arr2 = [
  { uid: 2, name: "smth else", description: "cucarecu" },
]
const mynewObject2 = { uid: 1, name: "newBlabla", description: "newDesc" };

const arr3 = []
const mynewObject3 = { uid: 1, name: "newBlabla", description: "newDesc" };

function addOrReplace (arr, obj, idx) {
  return (idx = arr.findIndex(x => obj.uid === x.uid) > -1 ? arr[idx] = obj : arr.push(obj)), arr;
}

console.log(addOrReplace(arr1, mynewObject1));
console.log(addOrReplace(arr2, mynewObject2));
console.log(addOrReplace(arr3, mynewObject3));

For a more concise version that does not require returning the array:

const arr1 = [
  { uid: 1, name: "bla", description: "cucu" },
  { uid: 2, name: "smth else", description: "cucarecu" },
]
const mynewObject1 = { uid: 1, name: "newBlabla", description: "newDesc" };

const arr2 = [
  { uid: 2, name: "smth else", description: "cucarecu" },
]
const mynewObject2 = { uid: 1, name: "newBlabla", description: "newDesc" };

const arr3 = []
const mynewObject3 = { uid: 1, name: "newBlabla", description: "newDesc" };

function addOrReplace (arr, obj, idx) {
  idx = arr.findIndex(x => obj.uid === x.uid) > -1 ? arr[idx] = obj : arr.push(obj);
}

addOrReplace(arr1, mynewObject1)
console.log(arr1);

addOrReplace(arr2, mynewObject2)
console.log(arr2);

addOrReplace(arr3, mynewObject3)
console.log(arr3);

Answer №2

function updateArray(arr, object) {
    arr = arr.filter(element => element.id !== object.id);
    arr.push(object)
    return arr;
}

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

Learn how to incorporate latitude and longitude coding into PHP to display a map icon that correctly redirects to the desired URL when clicked

I am in need of a table that includes buttons for adding, editing, deleting, and mapping. Everything works fine so far, but when I click on the map button, it should take me to Google Maps with coordinates linked from a MySQL database containing latitude ...

Click to reveal the Drop-Up Menu

Looking for a way to create a dropdown menu that opens upwards without using complex scripts? The click events for closing the menu seem to be causing some bugs. Any advice on achieving this using jQuery or JavaScript? Here is the HTML code: <div clas ...

The @mouse-down event in Vue does not seem to be firing

I'm new to web development and I'm having some issues with Vue. I learned from a tutorial that I can use @click when a button is pressed, and it works fine. Now I want to create a simple mechanism to detect when the mouse is clicked and released ...

Unable to click on options field for selection

My collection consists of various countries const countries = [{ name: 'United States', value: 'US', currency: 'USD' }, { name: 'Israle', value: 'IL', currency: 'ILS' }, { name: 'Unit ...

Utilize JavaScript to enclose every piece of text within single quotes in a span element

I have a tiny snippet of text: "some sample text" just a little more "additional text" I am trying to figure out how to wrap all the content between quotation marks in a span container, similar to what hilight.js does. I've been struggling to make it ...

JavaScript runtime error: Unforeseen exception code 0x800a138f has occurred

Encountering an exception when attempting to add a rule to a Radiobutton List using the rules() method. Error found at line 3747, column 3 in 0x800a138f - JavaScript runtime error: Unable to get property 'jQuery223064526755237397352' of undefin ...

Is there a way in JavaScript or jQuery to display text from an array and switch to the next piece of text in the array with the click of a button?

I currently have an array containing 13 items, all of which are text. To display the text from the array, I am using: document.write(arrayname["0"]); However, I would like to implement a functionality where users can click a button to fade out the curren ...

Creating Shapes in Leaflet: A Step-by-Step Guide to Drawing Like a Painter

I am attempting to utilize the plugin https://github.com/tcoupin/leaflet-paintpolygon for image annotation in a multipoint circle shape. Unfortunately, the plugin is not functioning correctly as a result of a bug present in the libraries it relies on. Ar ...

The subsequent menu selection will be based on the chosen menu value

I am attempting to accomplish the following: https://i.sstatic.net/JffUWC02.png Essentially, I need a select options menu with labels where selecting an option will display a corresponding value. These values should then become labels for a second selec ...

Unable to dynamically add class during rendering - React/Gatsby

I have the following component set up: const displayImage = false; ... <PostsGrid posts={filteredPosts} defaultCoverImage={defaultCoverImage} imageDisplay={displayImage} /> PostGrid.js ... console.log(displayImage)// ...

Tips for executing flushall just once across various clusters with Node.js and Redis

Whenever my server starts up, I find myself needing to clear out the Redis memory. However, each time a new cluster is formed, it triggers a flushall command that wipes out everything in memory. Is there a way to only run flushall once on the very first se ...

What are some techniques for animating SVG images?

Looking to bring some life to an SVG using the jQuery "animate" function. The plan is to incorporate rotation or scaling effects. My initial attempt with this simple code hasn't yielded the desired results: $("#svg").animate({ transform: "sc ...

Using JavaScript to convert date and time into ISO format

Similar Question: How do I output an ISO-8601 formatted string in Javascript? I've been attempting to change a date and time input into an ISO format but keep encountering the error .toISOString is undefined. It seems like I must be overlooking s ...

Attempting to extract text by utilizing the getText() function in Selenium along with Javascript

Attempting to use the getText() method in Selenium and Javascript, but encountering issues. const {Builder, By, Key, until} = require('selenium-webdriver'); (async function example() { let driver = await new Builder().forBrowser('chrom ...

I must utilize the MongoDB native driver to retrieve unique IDs sorted by a timestamp column

I am currently utilizing the nodejs mongodb native driver for developing a chat application. Within my database, I have a collection named dialog which contains fields for sessionId and dateCreated (timestamp). My objective is to retrieve a list of distinc ...

Understanding the functionality of tooltip-trigger in Angular

Whenever the value of my tooltip is invalid, I want it to be shown on keyup. However, for some reason <input name="myInput" tooltip-trigger="{{{true: 'keyup', false: 'blur'}[true]}}" ... it always displays the tooltip, <input n ...

What is the best way to display converted value in Angular 8?

In my current project, I am utilizing .NET Core 2.2 for the backend and Angular 8 for the frontend. The scenario involves having integer values on the backend within a specified range. For example: [Required] [Range(1073741824, 1099511627776)] // ...

Prevent event bubbling on a link generated by an Angular directive that includes transclusion

I am currently developing a directive that adds a link to a DIV element through transclusion. However, I am facing an issue where I want to execute specific functionality when the link is clicked without being redirected to the dummy href (in this case goo ...

Creating dynamic 2-dimensional math matrices using malloc

While a similar question has been posed before, such as in this post: Malloc a 2D array in C I am interested in determining whether it is more advantageous to utilize a traditional 2D array structure (employing pointers of pointers) or if opting for a fl ...

Learn the steps for converting data from xlsx or csv files into JSON format

I am currently working on developing an application that allows users to upload xlsx or csv files from the frontend and submit them to a backend built with nodejs and express for processing. However, when I receive the data in the backend, it appears in th ...