What is the best approach in JavaScript to compare and modify properties in two arrays of objects with efficiency?

Here's a method I have written in an Ecma 6 component (Salesforce Lightning Web Components for anyone interested). I am sharing it here because this is more focused on JavaScript rather than LWC. Do you think this is the optimal approach to solve this issue?

I have two arrays, both containing objects: My goal is to compare these arrays and create a new array of objects with a new property required: true or required: false. Is there a more efficient way to achieve this?

const RequiredFields = 
  [ { fieldApiName: 'FirstName', value: 'Test'         } 
  , { fieldApiName: 'LastName',   value: 'LastNameTest' } 
  ]

const AllFields = 
  [ { fieldApiName: 'FirstName', value: 'Test'         } 
  , { fieldApiName: 'LastName',   value: 'LastNameTest' } 
  , { fieldApiName: 'Suffix',     value: ''             } 
  ] 

addRequiredFields(RequiredFields, Allfields) {
  RequiredFields.forEach(field => {
    field.required = true; 
  });

  Allfields.forEach(field => {
    var hasVal = Object.values(field).includes(true); 
    if (hasVal) {
      console.log(field.fieldApiName + ' = TRUE'); 
    } else {
      field.required = false; 
    }
    console.log(field); 
    
  });
  return Allfields;  
}

console.log ( addRequiredFields(RequiredFields, Allfields) )

output =  [ 
    { fieldApiName: FirstName, value: 'Test' , required: true} 
  , { fieldApiName: LastName,   value: 'LastNameTest' , required: true} 
  , { fieldApiName: Suffix,     value: '', required: false            } 
  ] 

Answer №1

Here are some helpful suggestions:

  • Your code snippet
    var hasVal = Object.values(field).includes(true);
    may lead to bugs as it will return true if any key is assigned the value true. It's recommended to only check the value assigned to the key required.
  • Consider using the .map() method instead of directly mutating the array AllFields. Immutable programming can often result in simpler and easier-to-follow code.

Check out the simplified solution below utilizing .map() and .some():

const RequiredFields = [
  { fieldApiName: 'FirstName', value: 'Test'},
  { fieldApiName: 'LastName', value: 'LastNameTest' }
];

const AllFields = [
  { fieldApiName: 'FirstName', value: 'Test'},
  { fieldApiName: 'LastName', value: 'LastNameTest' },
  { fieldApiName: 'Suffix', value: ''}
];

const result = AllFields.map(field => ({
  ...field,
  required: RequiredFields.some(
    ({fieldApiName}) => fieldApiName === field.fieldApiName
  )
}));

console.log('result', result);

Answer №2

To achieve this, utilize the Array.some() method

const
  MandatoryFields = 
    [ { fieldApiName: 'FirstName', value: 'Test'         } 
    , { fieldApiName: 'LastName',  value: 'LastNameTest' } 
    ]
, Allfields = 
  [ { fieldApiName: 'FirstName', value: 'Test'         } 
  , { fieldApiName: 'LastName',  value: 'LastNameTest' } 
  , { fieldApiName: 'Suffix',    value: ''             } 
  ];

function addMandatoryFields( MandF , data)
  {
  data.forEach( row =>
    row.mandatory = MandF.some( x =>
      x.fieldApiName === row.fieldApiName 
    ) )
  }

addMandatoryFields( MandatoryFields, Allfields )

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

What is the best way to ensure an AJAX get-request waits for the page to finish rendering before providing a response?

I've been working on a Greasemonkey Script for a specific section of this website (Site1). Site1 offers various deals and discounts, and my script is designed to perform the following task: When a user visits an offer on Site1, the script checks with ...

Utilizing Multiple Components on a Single Page in React.js

I'm currently setting up a React main page that renders two separate components - Header and Test. render() { return ( <Header /> <Test /> ); } The Header component contains static content, while the ...

Ways to keep the position of an expanded collapsible table from Material UI intact

I found a collapsible table code snippet on this website: https://mui.com/material-ui/react-table/#collapsible-table However, there seems to be an issue where when I expand a row, the table "grows up" as it increases in size. This behavior is not ideal. I ...

Display only specific PHP-encoded JSON data in a formatted table

After receiving a variable from PHP, I convert it to JSON as shown below: var myData = <?php echo json_encode($json_array) ?>; When I log the output, it looks something like this: 0: Carat: "0.70" Clarity: "VVS2" Color: "D" Cut: "Very Good" Polish ...

"Troubleshooting: jQuery Find function not functioning correctly with HTML template

I am having trouble with a Shopify liquid code that I am trying to load into an HTML template <script type="text/template" id="description"> <div class="product-ddd"> {{ product.description }} </div> ...

What causes a component to not update when it is connected to an Array using v-model?

Array1 https://i.stack.imgur.com/cY0XR.jpg Array are both connected to the same Array variable using v-model. However, when changes are made to Array1, Array2 does not update. Why is this happening? Process: Upon examining the logs, it can be observed th ...

Is there a way to trigger a function upon the loading of a template in Angular 2?

I'm a newcomer to angular2 and I need to trigger a function when a template loads or initializes. I have experience with achieving this in angular1.x, but I'm struggling to figure out how to do it in angular-2. Here's how I approached it in ...

Issue: angular2-cookies/core.js file could not be found in my Angular2 ASP.NET Core application

After spending 2 hours searching for the source of my error, I have decided to seek help here. The error message I am encountering is: "angular2-cookies/core.js not found" I have already installed angular2-cookie correctly using npm. Below is the code ...

Improving Performance When Handling Multiple Events with Socket.io

Exploring socket.io event handling. Which is the more effective approach: socket.on('message', function (message) { if(message.message1) { // perform action } else if (message.message2) { // take alternative action } else ...

Ways to change the URL post saving a cookie with express?

I have written this code for user login in my Express router: if (password === realpassword) { res.cookie('thecookie', 'somethingliketoken'); res.redirect(302, '/somepages'); } else { res.status(403).end(); } The ...

Are strings in an array being truncated by Firebug console log?

I have a unique function for logging messages to the firebug console that I'd like to share: // Just having fun with names here function ninjaConsoleLog() { var slicer = Array.prototype.slice; var args = slicer.call(arguments); console.lo ...

Guide on generating a JSON dataset by combining two arrays and sending it back to an AJAX request

key:[id,name,address] value:[7,John,NewYork] I would like to generate a JSON object similar to {"id": 7, "name": "John", "address": "NewYork"} using a for loop, and then send it back to ajax $.ajax({ //what should be ...

Error encountered with MobileFirst version 8 and Angular JS v1.5.3 integration using Bootstrap

I am encountering an issue with my Cordova application that integrates with MobileFirst Platform version 8, Ionic version 1.3.1, and AngularJS version 1.5.3. Upon bootstrapping AngularJS to connect the app to MobileFirst Platform, I encounter the following ...

Resolution for Vue3: Understanding why a component instance's template ref cannot locate a defined function

LoginInfo.vue <script setup lang="ts"> import { rules } from './config/AccountConfig' import { reactive } from 'vue' import { ref } from 'vue'; import { ElForm } from 'element-plus'; const info = reac ...

I'm having trouble with my basic routing set up and I'm struggling to understand why it's not working

I'm currently working on a node tutorial and facing some challenges with my routes.js file. Previously, everything was functioning well today as the Node server was able to read the file. However, it seems to be ignoring it now for some unknown reaso ...

Angular's $routeProvider fails to navigate

I'm facing an issue with my Angular JS application where the $routeProvider doesn't load the template in the ng-view section. I have set up <html data-ng-app="myApp"> and <section data-ng-view></section. The template doesn't ...

Querying specific data from the API using unique identifiers

If the api.football-data.org/v1/competitions holds this data: { "_links": { "teams": { "href": "http://api.football-data.org/v1/competitions/444/teams" } }, "id": 444, "caption": "Campeonato Brasileiro da Série A", ...

looping through an ajax function with addEventListener

Apologies in advance for any errors in my English. My task involves creating a simple webpage with just 2 links. When one of these links is clicked, it should load the content of a specific .html file on the same page. For example: clicking on link 1 (wi ...

Trying to use the `await` keyword results in a "SyntaxError: Unexpted identifier" message, even when used within an `async` function

Encountering an error with Javascript's await when using it inside an async module let ImagesArray = await getImages(); ^^^^^^^^^ SyntaxError: Unexpected identifier at createScript (vm.js:80:10) at Object.runInThis ...

React app experiencing crashes due to Material UI Select component issues

I am facing a challenge while trying to incorporate a material ui select component into the React application I am currently developing. Whenever I attempt to add a select functionality to a form, it results in a crash. Despite following the example provid ...