Ways to update property values of an array object in JavaScript

I am trying to match values from one array object with another array and update the status if there is a match. Here's the desired output for arrObj:

[
    { name: "Test1", status: true }, 
    { name: "Test2", status: false }, 
    { name: "Test3", status: true }
]

Check out the demo here: https://stackblitz.com/edit/github-7plax5-mu3l6a?file=src%2Fapp%2Fapp.component.ts

let arrObj = [{
    name: "Test1",
    status: true
  },
  {
    name: "Test2",
    status: true
  },
  {
    name: "Test3",
    status: true
  }
]

let arr = ["Test1", "Test3"];

for (k of arr) {
  if (arrObj.name == k) {
    arrObj.status = true;
  }
}

console.log(arrObj);

Answer №1

Easiest way to update the original array

arrObj.forEach(item => item.status = arr.includes(item.name))

console.log(arrObj);
<script>
let arrObj = [{
    name: "Test1",
    status: false
  },
  {
    name: "Test2",
    status: false
  },
  {
    name: "Test3",
    status: false
  }
]

let arr = ["Test1", "Test3"];
</script>

Typescript version executes the same script as previously shared with type inference

Answer №2

Make sure to iterate over the correct array.
Start by looping through arrObj and then verify if the value is present in the array using the indexOf() method.

let arrObj = [{
    name: "Test1",
    status: false
  },
  {
    name: "Test2",
    status: false
  },
  {
    name: "Test3",
    status: false
  }
]

let arr = ["Test1", "Test3"];

arrObj.forEach(function(k) {
  if (arr.indexOf(k.name) != -1) {
    k.status = true;
  }
});

console.log(arrObj)

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

The Angular JavaScript code displays the message variable in the web browser

When using Angular JavaScript, the browser displays {{message}}. I have tried multiple approaches but it still doesn't work as expected. var myApp=angular.module("mod",[]); myApp.controller("con", function($scope){ $scope.message = "hhhhhhhh"; }); ...

Error: The image preview feature is malfunctioning in the Javascript code

Let me start by explaining the code. There are two views where I create a preview of an image from an input file. The first view contains a form for creating a project: <table> <tr> <td> <img src="" ...

Retrieve Cookie from a designated domain using Express

I am currently working on a React application that communicates with a Node/Express backend. To ensure the validity of requests, I am sending a cookie created by react-cookie from the React app to the Express app. To avoid issues related to naming conflict ...

When working with Vue 3, remember that inject() function is only allowed within setup or functional components

I'm puzzled as to why I keep encountering this error. I am attempting to utilize the Vuex store in a composition function, but for some reason, it keeps throwing an error regarding inject (even though I'm not using inject at all). My application ...

Problem with custom anchor component in React that needs to perform an action before being clicked

React Component (Custom Anchor) import React from 'react'; class Anchor extends React.Component { onClick = (event) => { // ----------------------------- // send Google Analytics request ...

Is CefSharp compatible with JavaScript promises?

I noticed that when I run the JavaScript code below in the console of my browser, it works perfectly fine. However, when I try to use this code in CefSharp, it returns null. I am currently using CefSharp version 100.0.120-pre. Does CefSharp 100.0.120-pre s ...

Is it possible to obtain the impending exception handling protocol in advance?

In upcoming scenarios, unhandled promise rejections will lead to the termination of the Node.js process using a non-zero exit code. Despite encountering issues, my pipeline erroneously passed and deployed a faulty version that crashes upon launch. If Node ...

Your request was denied by the Google Maps API server due to an invalid request. Please include the 'size' parameter in your request

I need to incorporate a static Google Map into my application built on node.js. Here is the code snippet: .panel.panel-primary .panel-heading h2.panel-title On the map .panel-body img.img-responsive.img-rounded(src="http://maps.googl ...

How to update razor page content dynamically in ASP.NET Core without refreshing the entire page using JavaScript/jQuery

I have a question about reloading a table on my webpage automatically. I want the page to reload every second based on the value entered in an input field, without the need to click any buttons. Here is what I have tried: <input id="txtRefresh&quo ...

Angular.js encountered an error at line 13550: [ng:areq] The argument 'popCntrl' is expected to be a function, but it was undefined

I have been diving into learning AngularJS on my own recently, and I've been attempting to create a basic popup feature. However, I keep encountering the error mentioned in the title. While searching for solutions, I haven't found any examples th ...

I am currently experiencing difficulties with uploading an image from the admin panel in Magento 1.9. Instead of receiving the expected response, I am

I encountered an error while trying to upload a file in Magento for a product image. When I click on upload, an error is displayed during the file upload process. Upon further investigation in the product.js file for item response, I noticed that HTML is b ...

varied reactions between componentDidMount and useEffect when employing jquery emoji plugin

Currently, I am facing an issue with a jquery emoji plugin that I need to use on one of my components until I complete building a custom plugin. Interestingly, when I call the emoji plugin inside componentDidMount, everything works fine, except for the ab ...

Modifying JavaScript using JavaScript

I'm looking for a solution to change the URL of a button in sync with the iframe displayed on the screen using JavaScript. The challenge I'm facing is figuring out how to dynamically update the button's URL based on the iframe content. Here ...

Recognize different HTML components when an event occurs

My application is equipped with a multitude of buttons, inputs, and other elements that trigger different events. I am looking for a way to easily differentiate between each element and the event it triggers. For instance, consider the following snippet f ...

Storing my token in the cookie using setCookie is proving to be difficult for me

While trying to authenticate my site with nextAuth and nookies, I am facing an issue where the token is not getting stored in the cookie. The API sends back a token and a refresh, and even though storing the refresh works fine, the token just doesn't ...

Child element casting shadow over parent element

I am currently using box shadow for both the parent (.map) and child (.toggle-button): .map { position: fixed; top: 20px; right: 0; width: 280px; height: 280px; z-index: 9999; box-shadow: 0px 1px 6px 0px rgba(0,0,0,0.3); } .map ...

Angular index.html file can include a conditional script

I am currently working on an Angular project, where the index.html serves as the main entry point for the application, just like in any other Angular project. This file contains important links and configurations. Within the HTML code snippet below, you w ...

Sharing information between different pages in NEXT.js version 14

After performing a fetch and receiving a successful response containing data as an object, I use router.push to redirect the page to another one where I want to display the fetched data. const handleSubmit = async (event: any) => { event.preventDefa ...

CORS blocking Axios POST request to Heroku causing a Network Error 503

Using the MERN Stack, everything was functioning correctly until modifications were made to the UI (such as relocating code to different components and altering styles). The issue lies with a specific POST request, while other requests that utilize Axio ...

Retrieving properties from video element following webpage loading

I am trying to access the 'currentSrc' value from a video object in my code. Here is what I have: mounted: function () { this.$nextTick(function () { console.log(document.getElementById('video').currentSrc) }); }, Despi ...