Is there a quick way to swap out an item in a JavaScript array with just one line of code?

Consider an array containing various objects:

let newArray = [
  { name: 'Alice', score: 15 },
  { name: 'Bob', score: 30 },
  { name: 'Eve', score: 18 }
]

Is there a more concise way to replace Bob's object with a new object in the array like this:

let updatedScoreForBob = { name: 'Bob', score: 35 }

Instead of finding the index and updating, is there a simpler one-liner method?

Answer №1

Eliminating the need for the joeIndex variable entirely, you can streamline your code like this:

array[array.findIndex(x => x.name === newScoreForJoe.name)] = newScoreForJoe;

Answer №2

Although the solution may not seem very elegant, if you need to return an array with the same number of objects, you can try this approach:

Initial array:

let initialArray = [
  { name: 'bob', score: 12 },
  { name: 'Joe', score: 20 },
  { name: 'Sue', score: 25 }
]

The new object to be inserted:

let newScoreForJoe = { name: 'Joe', score: 21 }

The replacement line:

let joeIndex = initialArray.map(x => x.name === newScoreForJoe.name ? newScoreForJoe : x)

Answer №3

Feel free to experiment with this solution. Simply update the object's property value as needed.

array[1].score = 21;

Answer №4

If you want to update an object in an array based on a condition, you can utilize the Array#some method and perform the assignment within the callback function.

In the code snippet below, we have an array of objects containing names and scores. We are looking for a specific name ('Joe') and updating its score if found. If the object is not found, no changes are made:

let array = [{ name: 'bob', score: 12 }, { name: 'Joe', score: 20 }, { name: 'Sue', score: 25 }],
    newScoreForJoe = { name: 'Joe',score: 21 };
    
array.some((a, i, aa) => (a.name === newScoreForJoe.name && (aa[i] = newScoreForJoe)));

console.log(array);

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

Adjust the color of the navbar only after a user scrolls, with a slight delay rather than

My code changes the navbar colors when I scroll (200ms). However, I would like the changes to occur when I am slightly above the next section, not immediately. In other words, what adjustments should I make to change the color in the next section and not ...

Link the ServerResponse object to a function

I'm new to ES and facing an issue with binding ServerResponse object to a function. My server follows OAuth protocol: let saveToken = (response) => { console.log('\n') console.log(this.constructor) // Issue [Function: Object ...

HyperText Markup Language, Cascading Style Sheets, and JavaScript

In my div, I have a combination of icons and text. I'm trying to center only the text within the div, with two icons on the left and 4 to 5 icons on the right. Although I managed to position the icons correctly, I am having trouble aligning the text ...

Complete the ship battle game board with C pieces

I've been tasked with creating a project for the ship battle game that features a 10x10 field. Right now, my main focus is figuring out how to randomly generate the positions of the ships within the field (which is represented by a 10x10 array). The s ...

Using Jquery Ajax to validate login information by submitting an HTML form

Working on a project involving jQuery Ajax, HTML forms, MySQL, and PHP. I have a database with registered users and I want to use a login form to retrieve user information from the database upon submission. However, I'm encountering an issue where the ...

What are the steps to make a counter-clockwise dial with jQuery Knob?

Is there a way to use multiple instances of jQuery.countdown? Can I create countdown circles using jQuery Knob? Find examples here and here. Using Multiple instances of jQuery.countdown <div data-countdown="2016/01/01"></div> <div data-co ...

Loading forms on page load in CodeIgniterWould you like to

Is there a way to include onload javascript in CodeIgniter forms? I want to be able to do something like this within CodeIgniter: form onload="yourscript" Since CodeIgniter uses the form_open() command, I'm unsure how to incorporate the onload scrip ...

Tips for concealing uib-popover when clicking outside of the popover in Angular JS

<button class="btn btn-default blue btn-lg h-ask btn-block" popover-placement="bottom" uib-popover-template="popover_home.templateUrl">ASK</button> In the code snippet above, there is an angular js popover implementation within an html templat ...

Choose a Vue filter according to the variable selected

My Current Table Dilemma Creating a table from a 2D array in Vue2 has been successful for me, as I've managed to display all the values correctly. However, I am facing issues with formatting. The template code is structured like this: <table> ...

Is it possible for a button to simultaneously redirect and execute a function using asynchronous JavaScript?

After browsing through several related posts, I realized that most of them were using href to redirect to a completely new webpage. However, in my JavaScript code, I have a button that utilizes the Material-UI <Link>. <Button component={Link} to= ...

The error message "Unable to push property in an undefined array" is displayed when attempting to push a property into

I'm struggling to debug the error message TypeError: Cannot read property 'push' of undefined. The following code snippet is what's causing the problem: const parent_lead_contact = this.props.parentLeads?.filter((lead) => lead. ...

Employing JavaScript to overlay multiple transparent images on top of each other

I am envisioning a dynamic sandwich assembly tool where users can customize their sandwich by selecting different ingredients. By using radio buttons, I hope to visually display the sandwich taking shape as each ingredient is selected. Rather than creati ...

Exploring the use of lists in the GO programming language

I've been attempting to create a test in GO, but I'm encountering difficulties with the list syntax within the struct. package primeFactor import "testing" var testCases = []struct { p int expected []int }{ {15, [3,5]}, ...

How to extract IDs from a URL in Angular

I'm facing an issue with retrieving the first id from an image URL. Instead of getting the desired id, I am receiving the one after the semicolon ("id" = 1). I have tried various methods but haven't been successful in resolving this issue. Any su ...

Encountered a Puppeteer Protocol issue: Error occurred when attempting to call a function on a closed

Exploring the world of JavaScript and nodejs as a beginner. Attempting to create a PDF table with node.js through Google puppeteer. Referenced a tutorial for the code below, all credit goes to the original source. Using a sample HTML template to populat ...

Tips for incorporating a favicon in a React application

Having trouble adding a favicon to my React application. I followed the instructions in this post, but it's not working for me. I placed the favicon.ico file inside the public folder where index.html resides. This is how my directory structure looks ...

Extracting a value from an array key in a stdClass Object: Step-by-step guide

I am currently developing a PHP web application and I need to extract a list of IDs from an array called $array. stdClass Object ( [users] => Array ( [0] => stdClass Object ( [id] => 90379747 [id_str] => ...

When a form filled out using JavaScript is submitted, Wicket is receiving blank values

I am attempting to create a cross-selection feature using two multiselect elements. When I click a button, a simple JavaScript function transfers a value from one multiselect to another. This functionality works well, but when I try to submit the form, I o ...

Issue with automatic form submission

What is the best way to automatically submit my form once the timer runs out and also when the refresh button is clicked? I have encountered an issue where every time I try to refresh the page, it prompts for user confirmation. If I click cancel, it stay ...

Issue with compatibility of jquery.ui.autocomplete.js on Internet Explorer 7

Having an issue with IE7 that shows an error message "'active.0' is null or not an object" on line 39, which reads: input.trigger("activate.autocomplete", [$.data(active[0], "originalObject")]); $("body").trigger("off.autocomplete"); This code ...