The closest comparison to the For In method in JavaScript in the Apex programming

I am looking for a way in Apex to iterate through all the fields of a list of account objects without having to resort to using JavaScript. Currently, I can achieve this with the following code snippet in JavaScript, but I prefer to keep things within the Apex realm whenever possible.

Is there an equivalent solution in Apex that functions similar to JavaScript's "IN" operator? I want to compare each field of one account to the corresponding field in the next account as shown below:

for (var key in dataGet.accounts[i]) {
     if (dataGet.accounts[i][key] != dataGet.accounts[i+1][key]) {
        dataGet.accounts[i][key] = dataGet.accounts[i+1][key];
     }
}

Any help would be greatly appreciated. Thank you!

Answer №1

If you want to access all fields in one record as key-value pairs, you can use

accounts[i].getPopulatedFieldsAsMap()

To compare all fields between two objects, even if they are not populated, look into "Dynamic Apex" and describe operations. This code will retrieve all API names on the object:

Map<String, Schema.SObjectField> fieldsMap = Schema.SObjectType.Account.fields.getMap();

You can then iterate over the map keys like this:

for(String field : fieldsMap.keySet()){
    System.debug(field + ': ' + accounts[i].get(field));
}

If you are working with classes that you cannot control and reflection is not available in Apex, you can try this approach. Serialize the objects to JSON and compare them:

public with sharing class Stack47339633{
    public String name, some, other, property;
    public Integer someInt;
    public Date d;
}

Stack47339633 obj1 = new Stack47339633();
obj1.name = 'hello';
obj1.some = 'world';
obj1.someInt = 13;
obj1.d = System.today();

Stack47339633 obj2 = new Stack47339633();
obj2.name = 'hello';
obj2.some = 'stackoverflow';
obj2.someInt = -7;
obj2.d = System.today();

Map<String, Object> o1 = (Map<String,Object>) JSON.deserializeUntyped(JSON.serialize(obj1));
Map<String, Object> o2 = (Map<String,Object>) JSON.deserializeUntyped(JSON.serialize(obj2));
Map<String, Object> o3 = new Map<String, Object>();

for(String s : o1.keySet()){
    System.debug(s + ':' + o1.get(s) + ' == ' + o2.get(s) + '?');
    if(o1.get(s) == o2.get(s)){
        System.debug('match!');
        o3.put(s, o1.get(s));
    }
}

Stack47339633 obj3 = (Stack47339633) JSON.deserialize(JSON.serialize(o3), Stack47339633.class);
System.debug('Full result: ' + obj3);
System.debug('Name : ' + obj3.name);
System.debug('someint : ' + obj3.someInt);
System.debug('d : ' + obj3.d);

While this method involves casting to JSON and back, it's effective. Serialization may fail in certain cases, but it's a viable option.

Check out these resources for more information:

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

Tips for preloading an ENTIRE webpage

I am looking for a way to preload an entire web page using JavaScript in order to have it cached in the user's browser. While I know how to preload images with JS, my goal is to also preload the entire page itself. For example, on my website, there ...

Encounter the error "Attempting to access object using Object.keys on a non-object" when attempting to retrieve all fields in request.body in Node.js?

I am working with a piece of code that handles the PUT method: module.exports.addRoutes = function(server) { //PUT server.put('/api/public/place/:id', function(request, response) { //this is just for testing, please do not care ...

Having trouble applying CSS styles to an element using JavaScript

Hello, I have an unordered list with some list elements and I am trying to apply a CSS style to highlight the selected list element. However, the style is not taking effect as expected. function HighlightSelectedElement(ctrl) { var list = document.ge ...

How can I use JQuery to save values from a for loop?

After working on a grid, I encountered an issue where only the last value was being returned when trying to fetch all values into an object. Unfortunately, I am stuck and unsure of how to resolve this problem. function item_details(){ var gridDataAr ...

Implementing a progress loader in percentage by simultaneously running an asynchronous setTimeout counter alongside a Promise.all() operation

I'm encountering a problem running an asynchronous setTimeout counter simultaneously with a Promise.all() handler to display a progress loader in percentage. Here are the specifics: I've developed a Vue application comprised of three components ...

I'm looking to display 9 images on a single page that rotate every 5 seconds between 3 different images. While I can figure out how to display one image easily, I'm

<script type="text/javascript"> var currPic = 1; var totPics = 9; var keepTime; function setupPicChange() { keepTime = setTimeout("changePic()", 5000); } function changePic() { currPic++; if (currPic > totPics) currPic = 1; var f ...

Unable to add JSON data to Javascript List Object? Consider using a combination of Node.JS and Firebase for a

router.get('/getMeals',function(req,res){ var mealsList = []; mealsList.push("bar"); mealsRef.on("value",function(data){ data.forEach(function(child){ console.log(child.val()); var newMeal = child ...

Tips for maintaining the browser scroll bar at the top when switching routes in AngularJS

How can I ensure that the scrollbar is always at the top when a user is redirected to a different page after scrolling down on the home page? The autoscroll feature in the code below doesn't seem to be working. Any suggestions would be greatly appreci ...

Pass the form data to the next page with javascript in HTML

While working on a website for a power plant, I encountered some issues that require assistance. The main problem is that our client does not want to set up a database on their server. This means I can only use html, javascript, and a bit of php. There is ...

Testing a Vue.js/Node.js application using Websockets

I'm working on a Vue project (version 3.0.3) integrated with a Node.js server. Can you provide guidance on how to conduct unit testing for this setup? The application is a game that relies on web-sockets for communication. ...

Issue with mapStateToProps not reflecting changes in props after localStorage modification

Currently, I am working on a redux application that involves authentication. My main concern right now is ensuring that the user remains logged in whenever they interact with the app. Below is a snippet from the bottom of my App.jsx file: function mapStat ...

What is the best method for performing cross-domain queries utilizing ajax and jsonp?

When attempting to send an ajax request to a specific URL, I encountered an error. Below is the code I used: $.ajax({ url: "http://webrates.truefx.com/rates/connect.html?q=ozrates&c=EUR/USD&f=csv&s=n", dataType : 'jsonp', ...

When multiple checkboxes are selected, corresponding form fields should dynamically appear based on the checkboxes selected. I attempted to achieve this functionality using the select option method

Require checkboxes instead of a selection option and have multiple checkbox options. Depending on the checked checkboxes, different form fields should appear. A submit button is needed. I have included some CSS code, but a more detailed CSS code is requir ...

Adjust the size of an element using the jQuery library's knob.js

There is a page Once the button is pressed, a circle element from the library jquery.knob.js appears. I am trying to change the size of the circle and have written this code: <div style="float:left; width:255px; height:155px"> <input ...

It appears that the jQuery.post() method is being overlooked or bypassed for unknown reasons

Trying to understand why the call to jQuery.post() isn't fetching the data or running the function after the fetch. Three files are included: an HTML file, a JavaScript file, and a PHP file. The HTML contains the modal element intended to appear when ...

Implementing automatic token refreshing and automatic logout features in Vue

I am a novice web developer looking to enhance my skills. For my initial project, I decided to incorporate Laravel and Vue. My main objectives are to: Implement an auto-logout feature after 3 minutes of user inactivity Create an automatic ping to my token ...

Tips for creating a multi-tenant application using Node.js (express.js)

I need help finding information on developing a multi-tenant application using Node.js. Can anyone offer some guidance? Thank you. My technology stack includes: Node.js Express.js Mocha.js Postgres SQL JavaScript HTML5 ...

React Native: struggling to fetch the most up-to-date information from an array

I'm working on a chat application that functions similar to a chatbot. Since I don't want to use a database and the messages are temporary, I opted to utilize JavaScript arrays. Whenever a user inputs a message in the TextInput and hits the butto ...

Tips for filling in the values for the options in a select dropdown menu

Currently, I am facing a strange bug related to the select element. Whenever I open the dropdown, there is always a mysterious black option at the top. This is how my HTML looks like: This particular element is part of my test controller. <select ng- ...

Conceal certain digits of a credit card number in a masked format for security purposes

Is there a reliable method to mask Credit Card numbers in password format within a text field? **** **** **** 1234 If you are aware of a definitive solution, please share it with us. ...