Accessing elements of both arrays and objects can be done by iterating through them using one code

Suppose I have a function that receives either an object or an array. The goal is to iterate through each element and perform some action on each element along the way. While looping through an array can be achieved using forEach() or a regular for loop, handling objects requires the usage of a for-in loop with an additional check using hasOwnProperty().

Is there a more universal approach that can handle both arrays and objects?

Here's my attempt at iterating through an object/array named 'value', but there seems to be no console messages displaying in case of objects:

keysArray = Object.keys(value);
for(let key in keysArray) {
    console.log(value[key])
}

Answer №1

You have the option to utilize a generator function called "entries" which iterates through an object or array:

function* entries(o) {
    if (Array.isArray(o))
        for (let i=0; i<o.length; i++)
            yield [i, o[i]];
    else
        for (const p in o)
            yield [p, o[i]];
}
// Another way is by using built-in iterators:
function entries(o) {
    return Array.isArray(o) ? o.entries() : Object.entries(o).values();
}

To use this function, you can call it as follows:

for (const [key, value] of entries(something)) {
    console.log(key, value);
}

Additionally, you can modify the function to only retrieve keys or values if needed.

Answer №2

// This function works with either objects or arrays

function performAction(data) {
  let myLoopable = data;

  // If the input is an object, convert it to an array
  if (!Array.isArray(data)) {
    myLoopable = Object
      .keys(data) // Retrieve keys as an array
      .reduce((accumulator, currentKey) => [...accumulator, data[currentKey]], []); // Get values as an array
  }

  myLoopable.forEach(element => console.log(element));
}

This code snippet serves as an illustration and not a foolproof solution. It's crucial to verify whether the input is an object or something else in order to ensure your function operates smoothly.

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

Sending information to a PHP script using Ajax

I am working on a project that involves input fields sending data to a PHP page for processing, and then displaying the results without reloading the page. However, I have encountered an issue where no data seems to be passed through. Below is my current s ...

"Enhance your visuals with a rotating light source in combination with a camera and Orbit

In my Three.js scene, I've integrated OrbitControls.js for rotation and panning functionality. However, I'm facing an issue with the lighting setup - I want the lighting to move along with the camera, ensuring that the object is always well-illum ...

Do you find encodeURIComponent to be extremely helpful?

I'm still puzzled about the benefit of using the JS function encodeURIComponent to encode each component of an http-get request when communicating with the server. After conducting some experiments, I found that the server (using PHP) is able to rece ...

How can I identify and return false if all the digits from 0 to 9 are matching with other characters in a string?

In my current project, I am focusing on filtering out numerical values only. I have implemented a phone mask using JavaScript on the front end to filter user input to a specific format such as (000)000-000, which includes numbers ranging from [2-9] and [0- ...

Generate a randomized array that can be utilized in all subsequent functions

Greetings! I am currently working on shuffling an array and using it in all my IBAction functions in the shuffled order. Below is a snippet of code similar to what I have: Class ViewController: UIViewController let numbers = [1,2,3,4,5] override func viewD ...

Retrieve the specific array element from parsing JSON that includes a particular phrase

I need help filtering array values that contain the phrase 'Corp' Currently, all values are being returned, but I only want the ones with "Corp" var url = "/iaas/api/image-profiles"; System.debug("getImageProfiles url: "+url ...

Encountering a 404 Error while using GetStaticPaths in NextJs

Having issues with Next JS dynamic routes resulting in a 404 Error. Initially attempted debugging by setting it up dynamically, then manually at http://localhost:3001/question/62e7b69ca560b1c81aa1a853 but still encountering the same issue. Tried toggling f ...

Unusual problem encountered with Chart.js bar chart, image dispersion

On my HTML page, I have integrated a stacked bar chart using the Chart.js library to visually represent data for users. The data changes based on user selection, and the JavaScript function that enables this onclick feature is: function aggLav(){ [... ...

Despite utilizing the 'on' function, JQuery is still unable to recognize elements that have been added through a backbone view

$(document).ready(function(){ $('.tagLines').on('mouseover', function(){ $(this).css("background-color","#ffffff").css("box-shadow", "0 0 4px 4px #C9C9C9"); }).on('mouseleave', function(){ $(this).css('background-color&ap ...

React - Issues with setTimeout() method not triggering following Promise.all execution

I am facing an issue with my arrow function that is called from the `componentDidMount` lifecycle method to fetch updated status of schedules every 20 seconds using a `setTimeout()`. The problem is that the `setTimeout()` method does not trigger another re ...

Optimizing JavaScript for efficient handling of large arrays

I'm currently developing an image editing program using JavaScript to expand my knowledge of the language. The images I am working with are typically around 3000 x 4000 pixels in size, resulting in a total of 48,000,000 values to manage when convertin ...

Utilizing ElementRef in Angular 4 to close dropdown when clicking outside of it

I recently came across this helpful tutorial, but I'm having trouble grasping how it actually functions. Here's the code snippet I've incorporated into my TypeScript file: @Component({ host: { '(document:click)': 'onOuts ...

Encountering an Error when Generating Facebook Website Audiences in JSON Format

I am currently working on a node.js script to generate Facebook audiences based on URL structure. However, I keep encountering the following error and cannot pinpoint what is wrong with the JSON data that I am sending: Error Received: FacebookRequestError ...

Why is the `node-config` configuration undefined within a TypeScript Jest environment?

I have a TypeScript module that is functional in both development and production environments. It utilizes https://github.com/lorenwest/node-config. When I attempt to import it into Jest for testing purposes, I encounter an error suggesting that the config ...

Sending data when button is clicked from Google Apps Script to sidebar

I have been attempting to pass a list that includes both the start cell and end cell of the active range. I want to then assign each value from this list to separate input fields. document.getElementById("btn-get-range").addEventListener('click&apo ...

AngularJS - Issue with retrieving the most recent entry during $routeChangeStart event

I am utilizing the $routeChangeStart function to redirect authorized users to specific URLs and prevent unauthorized access to special pages. In addition, I have dynamically generated pages that can be accessed via their unique page slugs. To achieve this ...

Aligning the 'container-fluid' slideshow and video player

I'm struggling to center a video in a slick slider that is set as a 'container-fluid'. The slideshow and video display fine across the full width of the browser, but when I resize the browser window or view the site on a lower resolution, I ...

Stop Jade from collapsing the directory hierarchy

When it comes to implementing a build solution using NPM scripts instead of Gulp or Grunt, I have been facing some challenges in managing multiple Jade files efficiently. I've referred to resources like and for guidance. The Jade CLI allows for com ...

Is it possible to fix the horizontal scrolling in Safari on an iPad?

Is there a method to prevent horizontal scrolling on Safari in iPad using JavaScript, CSS, or HTML? I added the following meta tag to try and adjust the viewport: <!-- Mobile viewport --> <meta name="viewport" content="width=device-width, ini ...

Checking if the current time falls within a specific time range, without taking the year into account, using Javascript

I am looking to add a special feature using JavaScript. I would like to change the background images of my webpage to ones related to Christmas during the holiday week, and have it repeat every year. How can I determine if the current date and time fall ...