What is the best way to check if an object exists in an array in JavaScript and update it if it does, otherwise add it as a new object in

I am working with an array of objects

const target = [{name: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89fafbe2c9eee4e8e0e5a7eae6e4">[email protected]</a>', selected: false, alertType: 'max'},
{name: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c7d7e7f5c7b717d7570327f73717573027577555c59717e72707077737e70735974787a">[email protected]</a>', selected: true, alertType: 'clear'},]

My goal is to update the array based on the name and alertType values. If a match is found, I will update the selected property. If no match is found, I will add a new object. Here's the new object:

 const newObj = {name: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1b2b3aa81a6aca0a8adefa2aeac">[email protected]</a>', selected: false, alertType: 'both'}

Answer №1

If you want to search for matching items, you can utilize the Array.find() method. This allows you to update an existing item if found, or add a new one if not:

const target = [
  {name: 'john.doe@example.com', selected: false, alertType: 'max'},
  {name: 'jane.smith@example.com', selected: true, alertType: 'clear'}
];

const update = { name: 'alice.white@example.com', selected: false, alertType: 'both' };

function updateAlerts(input, update) {
    let foundAlert = input.find(alert => ((alert.alertType === update.alertType) && (alert.name === update.name)));
    if (foundAlert) {
        foundAlert.selected = update.selected;
    } else {
        input.push(update);
    }
}

updateAlerts(target,  { name: 'bob.brown@example.com', selected: false, alertType: 'both' })
console.log(target);
updateAlerts(target,  { name: 'carol.green@example.com', selected: true, alertType: 'max' })
console.log(target);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Emphasize specific letters in a word by making them bold, according to the user

In my app, there is a search feature that filters data based on user input and displays a list of matching results. I am trying to make the text that was searched by the user appear bold in the filtered data. For example, if the user searches 'Jo&apos ...

Navigating Pre-Fetched Client Routes in Gatsby with @ReachRouter

Let's consider this scenario. Imagine a user enters /company/<company-id> in the address bar. Because the app is completely separate from the backend, it must prefetch the companies. The usual flow is /login -> /company/. Handling this sequ ...

Utilizing a React Hook to set data by creating a pure function that incorporates previous data using a thorough deep comparison methodology

I have come across the following code snippet: export function CurrentUserProvider({ children }) { const [data, setData] = useState(undefined); return ( <CurrentUserContext.Provider value={{ data, setData, }} & ...

Having trouble getting my Jquery Ajax post request to work with JSON data

I am working on syncing data from my Phonegap app back to the server. I have a PHP script set up on the server to handle the incoming data and now I need to figure out how to post values from my App to this script. Currently, I store my data in a SQLite d ...

Developing a fresh browser window with a clickable button using JavaScript

Currently, I am learning JavaScript and trying to create a button on a webpage using the code I wrote in JavaScript. However, instead of adding the button to the page specified by me, it is always added to index.html. I am using WebStorm IDE for this proje ...

Unspecified variables in a Javascript bot

Currently, I am working on a project involving the Kik API to create a bot. The main goal is for the game to initiate when users type "!hangman". A boolean value called hangman activates this process and then becomes inactive. Players can then input "!ha ...

Is your URL getting cut off in jQuery?

How can I properly display a URL in an HTML table without it getting truncated? I'm attempting to show it within a table using jQuery, but it seems to be cutting off the URL. Here's a snippet of my code. Any suggestions on how to fix this? <! ...

Display elements in an array of objects when the value changes with React

In my code, I am working with a nested list where each element has child nodes including id, name, and ancestors. The ancestors node contains an array of names and ids of the parent node, grandparent node, and so on. Here is an example: { "name": "Chi ...

Is there a way to determine the duration that a click was held down for?

When triggering an onClick event, I want to determine whether it was a single click or if the mouse button was held down for some time before releasing. This way, I can call the myTest() function within onClick="myTest()", which will log "mouse was click ...

What is the best way to create an index for a user-provided value in a textbox

Looking for guidance on how to set an index to user-provided values in a textbox, append them to a table in a new row, and display that index in the first column of every row. I am unfamiliar with this type of functionality. $(document).ready(function() ...

Creating an Angular directive that handles asynchronous attribute interpolation

I am facing an issue with my custom directive. In the link function attributes, I am trying to access the value of attributes.user. Here is how the directive is used in my view page: <div my-directive user="{{user.name}}"></div> The user obje ...

Error: The function `push` cannot be used on the variable `result` (TypeError)

Here is a snippet from my react component const mockFetch = () => Promise.resolve({ json: () => new Promise((resolve) => setTimeout(() => resolve({ student1: { studentName: 'student1' }, student2: { studen ...

Eliminate any blank brackets in a JSON structure

Looking to extract certain elements from a JSON string. Input : "sample": [{},{},{},{},{},{},{}], Output : "sample": [], Attempted solution : var jsonConfig = JSON.stringify(jsonObj); var result = jsonConfig.replace(/[{},]/g, ''); // Global ...

leveraging a Nuxt plugin and saving it in middleware

My goal is to create a middleware that validates the authentication and entitlement of users. The authentication details are retrieved from my store: //store/index.js const state = () => ({ auth: { isLoggedIn: false // more properties here } ...

What is the reason why calling setState does not update the local state?

Hello everyone, I came across an intriguing React task and I'm struggling a bit with finding the solution. Task: Can you figure out why this code isn't working and fix it? Code: class BugFixer extends React.Component { constructor(props) { ...

How can we determine the total character count of a file that has been loaded into a textarea

I have a textarea where I can count the number of characters as I type. function calculateCharacters(obj){ document.getElementById('numberCount').innerHTML = obj.value.length; } <textarea name="textField" id="my_textarea" class="text_edit ...

What is the rationale behind allowing any type in TypeScript, even though it can make it more challenging to detect errors during compile time?

Why is it that all types are allowed in TypeScript? This can lead to potential bugs at runtime, as the use of type "any" makes it harder to detect errors during compilation. Example: const someValue: string = "Some string"; someValue.toExponentia ...

Utilize AngularJS to interact with RESTful web services

Here is the JSON data fetched from my web service: [{"cameraid":"ggh","timestamp":"2016/05/10 01:31","filename":"ffffpg"}, {"cameraid":"mason","timestamp":"2016/05/10 05:31","filename":"aaa.png"} This is the HTML code I have: <!doctype html> <h ...

Transferring data between modules in nodejs

Within my custom module, there is a method designed to query the database and check if a given username exists. I need certain values to be returned in order to determine the query result at a higher level. var findUserbyUsername=function(username) { ...

Sending data using formData across multiple levels of a model in Angular

I have a model that I need to fill with data and send it to the server : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode ...