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

Is there a way to activate and change the color of a Radio Button when it is clicked?

Is there a way to change the background-color of a clicked Radio Button so it appears highlighted? For example, when the first choice is clicked, I want it to stand out visually. This is the current UI displaying the choices: https://i.stack.imgur.com/a7 ...

Guide to refining a JSON array using a pre-established list

I'm in need of assistance figuring out how to accomplish the following task: Below is the code snippet I am working with: public class Data { public string FirstName; public string LastName; public int Age; } var data = new Data { //this objec ...

Vue's v-on:click feature stops functioning correctly post-build

I have successfully integrated the Vue slide example from this link into my Angular template. Everything works fine when running ng serve, but after building with ng build and then trying to start it again with ng serve or from the dist folder using npm s ...

Is there a mistake in the TypeScript guide for custom typography in MUI5?

Currently, I am in the process of setting up custom typography variants in MUI5 by referencing this helpful guide: https://mui.com/customization/typography/#adding-amp-disabling-variants. As I follow step 2 and input the type definitions: declare module &a ...

Issue with the AngularJS build in Yeoman

After setting up Yeoman and Bootstrap for an AngularJS project, I utilized the grunt server command for debugging and coding. However, when I tried using the 'grunt build' command, it generated a dist folder. Unfortunately, when I attempted to ru ...

The feature to hide columns in Vue-tables-2 seems to be malfunctioning

The issue I'm facing is with the hiddenColumns option not working as expected. Even when I set it to hiddenColumns:['name'], the name column remains visible. I've updated to the latest version, but the problem persists. UPDATE I am tr ...

Application fails to launch after disabling unsafe-eval in the restricted Content Security Policy settings

Description My application is facing issues due to having a restricted CSP policy that does not allow unsafe-eval for scripts. When I add a Content-Security-Policy header without unsafe-eval, my application fails to load. Minimal Reproduction The restric ...

The function does not provide an output of an Object

I have two JavaScript classes, Controller.js and Events.js. I am calling a XML Parser from Events.js in Controller.js. The Parser is functioning but not returning anything: SceneEvent.prototype.handleKeyDown = function (keyCode) { switch (keyCode) { ...

Executing `removeChild` within a timeout during page load does not yield the expected results

I have an HTML div that is designed to contain dynamically generated children. These children are meant to be removed from the list after a specific amount of time (e.g. 1000 ms). Although some people have experienced scope issues with timeout functions, ...

Ajax is coming back with a value that is not defined

Currently, I am working on a search function that is responsible for searching a name from the database. When the user clicks "add", the selected item should appear below the search field so that it can be saved in the database. However, I am encountering ...

Issue encountered with the openpgpjs example: `'The function openpgp.encrypt is not defined'`

I encountered an issue with the 'openpgp.encrypt is not a function' error while attempting to follow the sample provided on the openpgp.js github page: https://github.com/openpgpjs/openpgpjs/blob/master/README.md#getting-started After following ...

What is the best way to retrieve the final value stored?

This is how I am using my Selector:- private loadTree() { this.loading = true; this.store.select(transitionListSelector).pipe().subscribe(data => { console.log(data); data.map(item => { console.log(item); this.tr ...

Error in TypeScript: Objects can only specify properties that are known, and 'state' is not found in type 'Partial<Path>'

As I strive to pass props through a React Router Link, my goal is to include all the user props. The code below is causing an error, particularly where state: {...employee} is highlighted. Although I am relatively new to TypeScript, I am actively working ...

Issue with displaying the Bootstrap-select DropDownList

Within my web application, I have a bootstrap-select combobox that I populate with data using an ajax call. Html: <div class="row"> <select id="selectGemeente1" class="selectpicker" data-live-search="true"></select> </div> Ajax ca ...

Utilizing CodeIgniter for Efficient AJAX Posting

I'm struggling to submit a post using the ajax post method. It appears that the request is being posted without any error messages, but the model doesn't seem to respond and insert the row into the database. While I'm not well versed in jQu ...

Develop a personalized conditional rendering directive in Vue.js

I am exploring how to create a custom Vue conditional directive. While I could simply use a global method and call it within a v-if, I prefer the idea of having a dedicated directive for clarity in my code. My objective is to apply this directive to an el ...

Enhanced string key indexer type safety in TypeScript

Discover and explore this online TypeScript playground where code magic happens: export enum KeyCode { Alt = 'meta', Command = 'command', // etc. } export type KeyStroke = KeyCode | string; export interface Combination { comb ...

Can a value be concealed within a dropdown list on a form (using PHP or JavaScript)?

Within my form, there is a drop down box listing the 50 states in the U.S. This list is generated using a PHP for loop. Users are required to select their residential state and later on, they must also choose a mailing state if it differs from their resi ...

Create a form with Vue that generates input fields based on JSON data and

I am seeking assistance with implementing a truncate filter for vueformulate in my project. I am generating the form from json data and need to limit the label to 80 characters, with a read more/less option. The data is dynamic, so changing the label in th ...

The 'import type' declaration cannot be parsed by the Babel parser

Whenever I attempt to utilize parser.parse("import type {Element} from 'react-devtools-shared/src/frontend/types';", {sourceType: "unambiguous"}); for parsing the statement, I come across an error stating Unexpected token, exp ...