Assign a property to an array of objects depending on the presence of a value in a separate array

Looking to manipulate arrays? Here's a task for you:

const arrayToCheck = ['a', 'b', 'c', 'd'];

We have the main array as follows:

const mainArray = [ {name:'alex', code: 'c'}, 
                    {name:'jack', code: 'd'}, 
                    {name:'john', code: 'n'}, 
                    {name:'mike', code: 'l'}
                  ]

The goal is to update the mainArray with a 'status' property, either 'enable' or 'disable', based on values in arrayToCheck.

Expected output:

[ {name:'alex', code: 'c', status: 'enable'}, 
  {name:'jack', code: 'd', status: 'enable'}, 
  {name:'john', code: 'n', status: 'disable'}, 
  {name:'mike', code: 'l', status: 'disable'}
]

An attempt using map and some methods to achieve this was made:

const output = this.mainArray.map( (fil, i) => {
          return arrayToCheck.some( s => {
            if (s === fil.Code) {
              this.mainArray[i].Status = 'enable'
            } else {
              this.mainArray[i].Status = 'disable'
            }
          })
        });

Answer №1

One way to achieve this is by utilizing the map method along with includes and spread syntax .... By doing so, a fresh array of objects is generated without altering the original array.

const itemsToCheck = ['a', 'b', 'c', 'd'];
const primaryArray = [ {name:'alex', code: 'c'}, {name:'jack', code: 'd'}, {name:'john', code: 'n'}, {name:'mike', code: 'l'}]

const updatedResult = primaryArray.map(item => ({...item, status: itemsToCheck.includes(item.code) ? "enable" : "disable"}))
console.log(updatedResult)

Answer №2

Here are a few things to consider:

  1. Remember that JavaScript is case-sensitive. This means that Code and code are treated as different properties.

  2. If you are not returning anything from your map callback function, then using a loop or forEach might be more appropriate than map.

  3. Instead of running an if statement inside the some function's callback, consider utilizing the return value of some. In your case, using includes may serve the same purpose without needing some.

If your objective is to modify the existing objects in the array, rather than creating new ones, you can follow this example:

const arrayToCheck = ['a', 'b', 'c', 'd'];

const mainArray = [ {name:'alex', code: 'c'}, {name:'jack', code: 'd'}, {name:'john', code: 'n'}, {name:'mike', code: 'l'}];

mainArray.forEach(entry => {
    entry.status = arrayToCheck.includes(entry.code) ? "enable" : "disable";
});

console.log(mainArray);

If your intention is to create new objects, refer to Nenad's answer for guidance on how to do so. However, based on your question, it seems like modifying existing objects was your goal.

Answer №3

Check out this simple code snippet:

    const arrayToCheck = ['a', 'b', 'c', 'd'];
    const mainArray = [ {name:'alex', code: 'c'}, {name:'jack', code: 'd'}, {name:'john', code: 'n'}, {name:'mike', code: 'l'}]    
    const output = mainArray.map(obj => {
            obj.status = arrayToCheck.indexOf(obj.code) < 0 ? 'disable' : 'enable';
            return obj;
        })
    console.log(output);

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

Developing a compressed file in JavaScript

async purchaseMultiple(decoded, purchaseData){ const user = await Database.user.findOne({where: { id_user: decoded.id_user }}); if( ! user) return [404, 'ERROR: User [' + decoded.id_user + '] not found']; if(user.credi ...

Ways to manage numerous AJAX actions within a single HTTP request?

Currently, I am utilizing jQuery to create a multipart web page containing a list of links that are updated through periodic AJAX HTTP requests. Each link on the page is triggered by a timer in JavaScript, causing it to make an HTTP request to its designat ...

What is causing all Vuejs requests to fail in production with the error message "javascript enabled"?

My vuejs application interacts with a REST API in Node.js (Express, MongoDB Atlas). Everything runs smoothly when I run the Vue app on localhost while the Node.js app is on the server. However, when I deploy my dist folder to the server, although the app ...

What are the steps to globalize the ng-bootstrap datepicker?

For my current project, I am utilizing the ng-bootstrap datePicker component. The demo for my simple datePicker widget can be found here. However, I am now seeking to internationalize it by setting it to use the Russian language. Any assistance with this ...

New solution for Java applet requiring communication with browser using JavaScript

Within our web platform, we have been utilizing a Java applet to interact with the MS Word application using jacob jar. This allows users to open, edit, and automatically upload files to the server upon saving. However, due to Google Chrome discontinuing ...

Using TypeScript, you can pass an object property name as a function argument while ensuring the type is

How can I define a type in a function argument that corresponds to one of the object properties with the same type? For instance, if I have an object: type Article = { name: string; quantity: number; priceNet: number; priceGross: number; }; and I ...

What are some strategies for establishing communication between sibling components in Vue?

Currently, my Vue app has a structure that includes a "blackout" component for displaying modals and a router-view for various sub-menus. These components are siblings at the same level. <blackout v-if="this.popup.currentPopup"></blacko ...

What are the steps for implementing a equirectangular image in WebXR with three.js?

Currently, I am developing a web application with Three.js that requires the use of equirectangular images for panoramic tours. My goal is to incorporate a feature that allows users to switch between normal mode and VR mode similar to React360 and AFrame. ...

JavaScript code to make titles slide in as the user scrolls

Looking for a better way to make all titles slide in upon scrolling instead of coding individually? Consider using a forEach loop! Here's how you can modify the code below: function slideInLeft() { document.querySelectorAll('.subtitle-left ...

Is there a way to dynamically register an external component in Vue3 without altering the main project?

In my current project, known as "ProjectMain," I am also working on another project that will act as an extension to ProjectMain - let's call it "MyComponent." My intention is to create MyComponent as a standalone library. My main question is: can I ...

Issues have arisen with the @keydown.ctrl and @keyup.ctrl event modifiers in Vue.js, as they are not properly responding

I have a project in VueJS where I need to implement a custom context menu that will pop up when the user hovers over specific elements on the page. This context menu is dynamic, meaning it changes as the user moves between different items. If the user hold ...

Tips for finding the correct file path for a .js file when utilizing the require function

I am currently working on an ExpressJS project and I am facing an issue with using a .js module inside another. Despite using require to retrieve the .js module, it appears that the path is incorrect which is preventing me from locating the module. How can ...

The unexpected blank space appearing beneath my website as a result of images and videos placed on the

There seems to be some random white space on my website between the main body elements and the footer. Interestingly, removing the cat image and videoplayer eliminates this white space. However, I don't want to remove them completely, so I'm tryi ...

What causes useEffect to trigger twice when an extra condition is included?

Attempting to create a countdown timer, but encountering an interesting issue... This code triggers twice in a row, causing the useEffect function to run twice per second. 'use client' import {useState, useEffect, useRef} from 'react' ...

Native JavaScript does not handle AJAX responses correctly

I'm facing an issue with my ajax call where the returned HTML works well on changes, but the Javascript that should perform actions based on clicks within the results is not functioning properly. Here is the ajax call: function update_order_shipp ...

How do I repeatedly invoke a function in JQuery that accepts two different arguments each time?

I have a collection of folders, each containing various images. The number of pictures in each folder ranges from 8 to 200. Folders are numbered from 1 to 20 and the images within them are also labeled numerically. My goal is to aggregate all these images ...

disable the form submission function in dropzone when buttons are clicked

Dropzone is being utilized on my page in the following manner alongside other input types such as text and select dropdowns: <form name="somename" method="post" action="/gotoURL" form="role"> // Other form elements here <div id="dropare ...

Updates to the AngularJS model are not appearing in the user interface

Despite executing the controller code, the values in the UI remain unchanged. The initial values are displayed without any issue. I've attempted to call $scope.$apply() at the end of each function (submit and transfer), but it didn't resolve the ...

Extract form input to utilize in nodemailer

Currently I am working on a form implementation where I intend to utilize nodemailer for sending test emails to myself. My goal is to have the email inputted into the form dynamically appear in both the "to" and "subject" fields when the user submits the f ...

What is the best way to showcase the information of each object on a click event in Vue.js?

My goal with this code is to display each day's class schedule when it is clicked on. However, the issue I'm facing is that the entire week's schedule is being displayed instead of just the selected day. What adjustments should I make in ord ...