Tips for updating the value of an Array of Objects using an array containing the desired string value

I have a scenario where I need to update the 'checked' key value to true for objects in an array based on another array's values.

var daysActive = ['monday', 'tuesday', 'wednesday'];

var weekDays = [{ "name": "Sunday", "value": "sunday", "id": "SUN","checked":false,disabled:true },
            { "name": "Monday", "value": "monday", "id": "MON" ,"checked":false,disabled:true},
            { "name": "Tuesday", "value": "tuesday", "id": "TUE","checked":false,disabled:true },
            { "name": "Wednesday", "value": "wednesday", "id": "WED","checked":false,disabled:true },
            { "name": "Thursday", "value": "thursday", "id": "THU","checked":false,disabled:true },
            { "name": "Friday", "value": "friday", "id": "FRI","checked":false,disabled:true },
            { "name": "Saturday", "value": "saturday", "id": "SAT","checked":false,disabled:true}
            ];

The final array should have its 'checked' key values updated as follows:

var resultantDays = [{ "name": "Sunday", "value": "sunday", "id": "SUN","checked":false, disabled:true },
                { "name": "Monday", "value": "monday", "id": "MON" ,"checked":true, disabled:true},
                { "name": "Tuesday", "value": "tuesday", "id": "TUE","checked":true, disabled:true },
                { "name": "Wednesday", "value": "wednesday", "id": "WED","checked":true, disabled:true },
                { "name": "Thursday", "value": "thursday", "id": "THU","checked":false, disabled:true },
                { "name": "Friday", "value": "friday", "id": "FRI","checked":false, disabled:true },
                { "name": "Saturday", "value": "saturday", "id": "SAT","checked":false, disabled:true}
                ];

I have attempted a solution, but the approach seems to be incorrect.

var modifiedWeekdays = daysActive.map(day => {
  weekDays.forEach(function(val) {
    if (val.value === day) {
       val.checked = true;
    }
  });
});

Answer №1

One way to check if a value exists in the `daysActive` array is by using the `map` function on the `weekDays` array.

var daysActive = ['monday', 'tuesday', 'wednesday'];

var weekDays = [{ "name": "Sunday", "value": "sunday", "id": "SUN","checked":false,disabled:true },
            { "name": "Monday", "value": "monday", "id": "MON" ,"checked":false,disabled:true},
            { "name": "Tuesday", "value": "tuesday", "id": "TUE","checked":false,disabled:true },
            { "name": "Wednesday", "value": "wednesday", "id": "WED","checked":false,disabled:true },
            { "name": "Thursday", "value": "thursday", "id": "THU","checked":false,disabled:true },
            { "name": "Friday", "value": "friday", "id": "FRI","checked":false,disabled:true },
            { "name": "Saturday", "value": "saturday", "id": "SAT","checked":false,disabled:true}
            ];
weekDays.map(day => {
    day.checked = daysActive.indexOf(day.value) !== -1;
});
console.log(weekDays);

Answer №2

Similar to the solution provided by @Vineesh :)

var daysActive = ["monday", "tuesday", "wednesday"];

var weekDays = [
  {
    name: "Sunday",
    value: "sunday",
    id: "SUN",
    checked: false,
    disabled: true
  },
  {
    name: "Monday",
    value: "monday",
    id: "MON",
    checked: false,
    disabled: true
  },
  {
    name: "Tuesday",
    value: "tuesday",
    id: "TUE",
    checked: false,
    disabled: true
  },
  {
    name: "Wednesday",
    value: "wednesday",
    id: "WED",
    checked: false,
    disabled: true
  },
  {
    name: "Thursday",
    value: "thursday",
    id: "THU",
    checked: false,
    disabled: true
  },
  {
    name: "Friday",
    value: "friday",
    id: "FRI",
    checked: false,
    disabled: true
  },
  {
    name: "Saturday",
    value: "saturday",
    id: "SAT",
    checked: false,
    disabled: true
  }
];

daysActive.forEach(dayActive => {
  const activeDay = weekDays.find(day => day.value === dayActive);
  activeDay.checked = !activeDay.checked;
});

console.log(weekDays);

Answer №3

const activateDays = (days) => {
    days.forEach(day => {
        const weekday = weekDays.find(wd => wd['value'] === day);
        if (weekday) {
            weekday.checked = true;
        }
    });
};
activateDays(daysActive);

Answer №4

You can implement Array.prototype.reduce() in conjunction with Array.prototype.includes()

Example:

const daysActive = ['monday', 'tuesday', 'wednesday'];
const weekDays = [{ "name": "Sunday", "value": "sunday", "id": "SUN","checked":false,disabled:true },
  { "name": "Monday", "value": "monday", "id": "MON" ,"checked":false,disabled:true},
  { "name": "Tuesday", "value": "tuesday", "id": "TUE","checked":false,disabled:true },
  { "name": "Wednesday", "value": "wednesday", "id": "WED","checked":false,disabled:true },
  { "name": "Thursday", "value": "thursday", "id": "THU","checked":false,disabled:true },
  { "name": "Friday", "value": "friday", "id": "FRI","checked":false,disabled:true },
  { "name": "Saturday", "value": "saturday", "id": "SAT","checked":false,disabled:true}
];
const resultantDays = weekDays.reduce((a, c) => [...a, c.checked = daysActive.includes(c.value), c], []);

console.log(resultantDays);
.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

When attempting to retrieve data saved to req.session with express-session from a different endpoint, the data appears to be

While working on my project with express-session, I encountered a peculiar issue. I am saving the currently logged in user to the session, but when I try to access the currentUser key on the get route, I find that the value is an empty object. Strangely, i ...

How can we efficiently trigger a function that sends an axios request by leveraging data from a v-for loop?

Currently, I am developing an e-commerce platform using Rails and VueJS. In order to display the orders of a specific user, I have created a component file. Within this component, I am utilizing a v-for loop to iterate over and showcase all the information ...

Encountering an error when attempting to upload documents and PDF files to Google Cloud through Firebase

My current project involves uploading basic documents using busboy / express.js to google cloud. However, I encountered this error message: Error: Cannot find module 'busboy/lib/types/node_modules/dicer' Here is the code snippet for the upload ...

Saving solely the content of an HTML list element in a JavaScript array, excluding the image source

One issue I am facing is with an unordered list in HTML which contains items like <ul id="sortable"> <li class="ui-state-default"><img src="images/john.jpg">John</li> <li class="ui-state-default"><img src="images/lisa.jpg ...

Custom filtering in Angular using ngTables is an advanced feature that allows

I am currently working on implementing custom filtering in ngTables, similar to this example. I have a set of columns with standard text input filters, but for some of them, I want to utilize my own filtering function instead of the default angular $filter ...

Utilizing UTC Time with AngularUI's UI-Date Datepicker

My issue lies with the datepicker using localized time instead of UTC when making calls to the backend. To handle this, I've created a function that adjusts the value before posting it to the server: function adjustDateForTimeOffset(dateToAdjust) ...

Setting up Quill in a Nuxt project (a VUE component)

I'm struggling to remove the toolbar in Quill despite my efforts. This is the HTML snippet I am working with: <template> <quill v-model="content" :config="config"></quill> </template Here's what I have inside the scri ...

What is the best way to implement the node.js function into a typical frontend JavaScript file?

I created a node.js puppeteer script to extract data on covid cases in Canada. Now, I want to integrate this function into a frontend website built with JavaScript to display information on Canada's covid cases. How can I export this function to a Jav ...

The JSONObject is returning an empty nested array

After retrieving a nested JSON array named "invested" from a JSON file, I encountered an issue where the array appeared to be empty when attempting to utilize it. The contents of my JSON file are as follows: { "invested": [ { &qu ...

Utilizing getter and setter functions within a setter with a type guard

I need to implement a getter and setter in my class. The setter should accept a querySelector, while the getter is expected to return a new type called pageSections. The challenge I'm facing is that both the getter and setter must have the same argum ...

Creating a simulation in THREE.js that incorporates MeshBasicMaterial, with the added feature of being able to

Creating a dungeon crawler game using three.js has been quite the learning experience. Initially, I opted for MeshBasicMaterial to ensure everything was uniformly visible in the dungeon. However, I wanted to experiment with adding bonus lights peeking thro ...

Apply a chosen style to the element that was clicked on, while removing the style from the rest

Here is an example of my ul li structure: <div id="categoryTree"> <ul> <li id="cat_15"> <a class="hasSubCat" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">N ...

Select a specific item from an array and reveal the corresponding item at the matching index in a separate array

I'm working on a project where I have a list of elements that are displayed using a ng-repeat and I am using ng-click to retrieve the index of the element in the array that I clicked on. Here is the HTML code snippet: <ul> <li ng-repeat=" ...

Exploring the compatibility of Next.js with jest for utilizing third-party ESM npm packages

Caught between the proverbial rock and a hard place. My app was built using: t3-stack: v6.2.1 - T3 stack Next.js: v12.3.1 jest: v29.3.1 Followed Next.js documentation for setting up jest with Rust Compiler at https://nextjs.org/docs/testing#setting-up-j ...

Utilizing the Loess npm module in conjunction with Angular 4

I am attempting to incorporate the Loess package into my project. The package can be found on NPM and offers various regression models for data fitting. I successfully installed it using npm install loess --save, and it now resides in the node_modules dire ...

Obtain offspring from a parent element using jQuery

$(document).ready(function() { $.ajax({ type: "POST", url: 'some/url', data: { 'name':'myname' }, success: function (result) { var result = ["st ...

SimpleLightBox refuses to function

Having trouble getting SimpleLightBox to work properly? It seems like when you click on an image, it opens as a regular image on a blank page. I've added the JS and CSS files correctly (I double-checked in the source code) and included the HTML and JS ...

Angular JS | Sending information to two separate controllers when clicked

I have a series of projects displayed in divs using ng-repeat. Each div contains a link with the project's id. My goal is to bind the project id on ng-click to update a factory. This will enable me to share the clicked project's id with another ...

Preventing horizontal swiping while vertically scrolling on mobile devices

How can I prevent horizontal swipe functionality from interfering with vertical scrolling on a webpage? I have successfully blocked vertical scrolling but need help finding a solution for preventing horizontal swiping. Has anyone else encountered this issu ...

Having trouble importing a package into my React boilerplate

Having trouble importing the react-image-crop package with yarn and integrating it into a react boilerplate. Encountered an error after installing the package: Module parse failed: /Users/...../frontend/node_modules/react-image-crop/lib/ReactCrop.js Unex ...