Use forEach its a built-in array function. Array.forEach():

yourArray.forEach(function (arrayItem) {
    var x = arrayItem.prop1 + 2;
    console.log(x);
});
Answer from Dory Zidon on Stack Overflow
🌐
Reddit
reddit.com › r/learnjavascript › loop through array and create object of specific key/value pairs?
r/learnjavascript on Reddit: Loop through array and create object of specific key/value pairs?
March 31, 2023 -

I've been searching without success for a way to process some data that arrives as an array of objects. I need to pull out specific data from each object and create a new object from that. I don't actually create the data but based on the way it's formatted when it gets to me, I can tell you the code below would give the same structure. Below that is json of what I need to reformat it as.

It's always the same number slots but they're not always in the order. If they were the order, I'd have no problem. I need the Name, value and mode from each object. Some instances of this don't have what is in this sample the third element and in such cases, mode is not needed.

I'm not hear asking anyone to actually write the code for me -- I prefer to actually learn how to do it. But I'm hoping someone can point me in the right direction.

TIA!

slots[slots.length]={"name":"Name1","task":"Task1"};
slots[slots.length]={"Value":"Current Value","temperature":67,"status":"on"};
slots[slots.length]={"mode":"Current Mode","status":"selected"};

I need to convert that to (I can drop the remaining data it's not needed for my task):

{slotsObj:{"name":"Name1","value":"Current Value","mode":"Current Mode"}}
Top answer
1 of 4
1
I stuck your whole post in chat GPT, lol: You can use a loop to iterate over the array of objects and create a new object with the required key-value pairs. Here's an example of how you could do it: // input array const slots = [ {"name": "Name1", "task": "Task1"}, {"Value": "Current Value", "temperature": 67, "status": "on"}, {"mode": "Current Mode", "status": "selected"} ]; // output object const slotsObj = {}; // iterate over the input array for (let i = 0; i < slots.length; i++) { const slot = slots[i]; // check if the current object has the required properties if (slot.hasOwnProperty("name")) { slotsObj.name = slot.name; } else if (slot.hasOwnProperty("Value")) { slotsObj.value = slot.Value; } else if (slot.hasOwnProperty("mode")) { slotsObj.mode = slot.mode; } } // create the final object with the required properties const result = { slotsObj }; console.log(result); // output: { slotsObj: { name: 'Name1', value: 'Current Value', mode: 'Current Mode' } } This code checks each object in the slots array for the required properties (name, Value, and mode) and adds them to the slotsObj object. Then it creates the final object with the required structure. Note that if an object doesn't have one of the required properties, it will simply be ignored.
2 of 4
1
slots[slots.length]={"name":"Name1","task":"Task1"}; That's the most unique way I've seen someone .push() onto the end of an array 👀. That's a first for me. As for your problem at hand, here's a more imperative way you could approach it. Create an empty "result" object. We're going to gradually add stuff to it until we get what we want. Loop through each slot in the slots array For each slot, check if it has one of the properties you care about. If it does, add that property to your result object.
Top answer
1 of 16
511

Use forEach its a built-in array function. Array.forEach():

yourArray.forEach(function (arrayItem) {
    var x = arrayItem.prop1 + 2;
    console.log(x);
});
2 of 16
322

Some use cases of looping through an array in the functional programming way in JavaScript:

1. Just loop through an array

const myArray = [{x:100}, {x:200}, {x:300}];

myArray.forEach((element, index, array) => {
    console.log(element.x); // 100, 200, 300
    console.log(index); // 0, 1, 2
    console.log(array); // same myArray object 3 times
});

Note: Array.prototype.forEach() is not a functional way strictly speaking, as the function it takes as the input parameter is not supposed to return a value, which thus cannot be regarded as a pure function.

2. Check if any of the elements in an array pass a test

const people = [
    {name: 'John', age: 23}, 
    {name: 'Andrew', age: 3}, 
    {name: 'Peter', age: 8}, 
    {name: 'Hanna', age: 14}, 
    {name: 'Adam', age: 37}];

const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true

3. Transform to a new array

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]

Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.

4. Sum up a particular property, and calculate its average

const myArray = [{x:100}, {x:200}, {x:300}];

const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300

const average = sum / myArray.length;
console.log(average); // 200

5. Create a new array based on the original but without modifying it

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => {
    return {
        ...element,
        x: element.x * 2
    };
});

console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]

6. Count the number of each category

const people = [
    {name: 'John', group: 'A'}, 
    {name: 'Andrew', group: 'C'}, 
    {name: 'Peter', group: 'A'}, 
    {name: 'James', group: 'B'}, 
    {name: 'Hanna', group: 'A'}, 
    {name: 'Adam', group: 'B'}];

const groupInfo = people.reduce((groups, person) => {
    const {A = 0, B = 0, C = 0} = groups;
    if (person.group === 'A') {
        return {...groups, A: A + 1};
    } else if (person.group === 'B') {
        return {...groups, B: B + 1};
    } else {
        return {...groups, C: C + 1};
    }
}, {});

console.log(groupInfo); // {A: 3, C: 1, B: 2}

7. Retrieve a subset of an array based on particular criteria

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}] 

Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.

8. Sort an array

const people = [
  { name: "John", age: 21 },
  { name: "Peter", age: 31 },
  { name: "Andrew", age: 29 },
  { name: "Thomas", age: 25 }
];

let sortByAge = people.sort(function (p1, p2) {
  return p1.age - p2.age;
});

console.log(sortByAge);

9. Find an element in an array

const people = [ {name: "john", age:23},
                {name: "john", age:43},
                {name: "jim", age:101},
                {name: "bob", age:67} ];

const john = people.find(person => person.name === 'john');
console.log(john);

The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.

References

  • Array.prototype.some()
  • Array.prototype.forEach()
  • Array.prototype.map()
  • Array.prototype.filter()
  • Array.prototype.sort()
  • Spread syntax
  • Array.prototype.find()
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › forEach
Array.prototype.forEach() - JavaScript - MDN Web Docs
The forEach() method is an iterative method. It calls a provided callbackFn function once for each element in an array in ascending-index order. Unlike map(), forEach() always returns undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.
🌐
Reddit
reddit.com › r/learnjavascript › how to loop through every array inside an array of arrays (and objects) with unknown depth?
r/learnjavascript on Reddit: How to loop through every array inside an array of arrays (and objects) with unknown depth?
November 9, 2023 -

Let's say I have an array like this:

mainArray = [
    0: {
        title: "Socials"
        chilren: [
            0 = {id: 1, title: "Twitter"},
            1 = {id: 2, title: "Facebook"},
            2 = {id: 3, title: "YouTube"}
        ]
    },
    1: {
        title: "Forums"
        children: [
            0 = {
                id: 1,
                title: "Car Forums
                children = [
                    MORESUBFOLDERS?,
                    MORESFILES?
                ]
            "},
            2 = {id: 3, title: "tech-forum.com"},
            3 = {id: 4, title: "fitness-forum,com"}
        ]
    },
    n: {...}
];  

This array represents a file structure with an unknown number of subfolders and files, with the main array being the root folder.

As you can see, each object inside the mainArray is a subfolder, these subfolder objects can contain an object representing a file, or an array inside an object representing a new subfolder. These sub-sub-folders can also have files as objects or subfolders as arrays, and this can go on for ever in theory. Obviously in practice there's limited depth, but the idea is to have a single function that traverses the entire data structure and returns something like:

rootFolder: {
    folder1: {
        subfolder1: {
            subfolderN {...}
            subfolderN {...}
            fileN
            fileN
        }
    }
    folderN: {
        subfolderN: {
            subfolderN {...}
            subfolderN {...}
            fileN
            fileN
        }
    }
};  

So I can render this as an HTML nested unordered list.

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-loop-through-an-array-containing-multiple-objects-and-access-their-properties-in-javascript
How to Traverse Array of Objects and Access the Properties in JavaScript? - GeeksforGeeks
July 23, 2025 - Object.keys() returns an array of a given object's own enumerable property names (keys). ... const a = [ {name: 'Saritha', sub: 'Maths'}, {name: 'Sarthak', sub: 'Science'}, {name: 'Sneha', sub: 'Social'} ] for (let teacher in a) { for (let key in a[teacher]) { console.log(a[teacher][key]); } } ... The outer for...in loop iterates over the array, where each teacher is the index of an object in the array.
🌐
2ality
2ality.com › 2011 › 04 › iterating-over-arrays-and-objects-in.html
Iterating over arrays and objects in JavaScript
April 20, 2011 - Combine Object.keys() or Object.getOwnPropertyNames() with forEach() array iteration. var obj = { first: "John", last: "Doe" }; // Visit non-inherited enumerable keys Object.keys(obj).forEach(function(key) { console.log(key); }); Other tasks: Iterate over the property (key,value) pairs of an ...
🌐
Attacomsian
attacomsian.com › blog › javascript-iterate-array-of-objects
Loop through an array of objects in JavaScript
June 10, 2023 - In JavaScript, you can loop through an array of objects using the forEach() method combined with the for...in loop. Consider the following code example that illustrates how to iterate over an array containing objects and print the properties ...
Find elsewhere
🌐
W3Schools
w3schools.com › js › js_array_iteration.asp
JavaScript Array Iteration
Create an Array Iterator object, containing the keys of the array:
🌐
DEV Community
dev.to › rahulbanerjee99 › javascript-do-you-know-the-fastest-way-to-iterate-over-arrays-objects-4b6h
JavaScript: Do you know the fastest way to iterate over arrays, objects? - DEV Community
October 22, 2021 - By Iterating over an array, I mean accessing the values. numbers.map( num => num ) /* OUTPUT On average it took 16.208858299255372 ms */ numbers.forEach( num => num ) /* OUTPUT On average it took 10.285145807266236 ms */ for (num in numbers) { num } /* OUTPUT On average it took 121.6859667301178 ms */ for (num of numbers) { num } /* OUTPUT On average it took 6.2104291915893555 ms */
🌐
Index.dev
index.dev › blog › javascript-object-iteration-methods
10 Effective Methods to Iterate Over JavaScript Objects
It only iterates over the object’s own properties, ignoring the prototype properties. Cleaner and more modern than for...in. Slightly less intuitive for beginners because it involves array methods. ... Object.values() if the values are all that matter to you and the keys are not. An array containing the values of the object's properties is returned by this function.
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
How do I force Javascript to Iterate over an Object in an Array? - JavaScript - The freeCodeCamp Forum
July 6, 2023 - I’m working on one of the intermediate algorithm scripting tasks in the Data Structures course and I can’t for the life of me get Javascript to iterate over the objects in an array passed to a function. It always iterates over the array indices. For example, if I type: for(let obj in collection) { console.log(obj) } the output is always 0 1 2 Your browser information: User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0 Challenge: Intermediate ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Object › entries
Object.entries() - JavaScript - MDN Web Docs
Using array destructuring, you can iterate through objects easily. ... // Using for...of loop const obj = { a: 5, b: 7, c: 9 }; for (const [key, value] of Object.entries(obj)) { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" } // Using array methods Object.entries(obj).forEach(([key, ...
🌐
freeCodeCamp
freecodecamp.org › news › loop-through-arrays-javascript
How to Loop Through Arrays in JavaScript
October 31, 2023 - When you have an array of objects, you can use the for...in loop to iterate through the properties of each object.
🌐
SheCodes
shecodes.io › athena › 262218-can-you-use-foreach-with-an-array-of-objects
[JavaScript] - Can you use forEach with an array of objects?
Learn how to use the forEach method in JavaScript to iterate over an array of objects and perform an action on each element.
🌐
Medium
medium.com › @francois.barrailla › javascript-iterate-over-array-values-and-indexes-using-a-for-of-loop-106a58972b24
JavaScript: Iterate over array values and indexes using a for-of loop | by François Barrailla | Medium
July 8, 2020 - We need to define a counter initialized to zero, then increment the counter by one until it reaches the size of the array. Then, for each iteration, we have to extract the value from the array when the index matches the current value of our counter.
🌐
Medium
medium.com › @louistrinh › iterating-through-javascript-objects-and-arrays-for-foreach-and-beyond-e9e6ce5376d3
Iterating Through JavaScript Objects and Arrays: for, forEach, and Beyond | by Louis Trinh | Medium
May 10, 2024 - Use Object.entries() to get key-value pairs as arrays and iterate over them: Object.entries(person).forEach(([key, value]) => { console.log(key, value); // Output: name Alice, age 30 }); Combine a forEach() loop with conditional checks within ...
🌐
Reddit
reddit.com › r/learnjavascript › loop through an array of objects and compare values. if value is not found, execute something else.
r/learnjavascript on Reddit: Loop through an array of objects and compare values. If value is not found, execute something else.
May 17, 2022 -

This is probably an easy problem but I just can't figure it out. I'll try to explain in detail within the test script.

// an array of objects obviously...
var loc = [ 
{"id":12345, "storeNumber":"0466"},
{"id":1235, "storeNumber":"566"}
]

//our number to match the "storeNumber". 
var sn = "466";

//If sn is found, we want to execute some code
loc.forEach(function(item) {
  if(sn == item.storeNumber) {
    //execute some code
  }

//if value does not exist, like it currently doesn't...Then I need to prepend a 0 to sn variable that is 3 letters in length.
}]

Here's my problem with this...As you can see the variable sn is 466. If there is no match, and the variable is 3 characters in length. I need to prepend a zero to it. sn would then be 0466.

0466 matches storeNumber with id 12345.

How would I go about getting the ID of 0466 if the first condition if(sn == item.storeNumber) doesn't match anything in the array of objects?

The problem here is that the forEach loop will loop through hundreds of records and return true for one if it is found. But that doesn't stop the loop from running, so everything after the loop would still be false, therefore I couldn't have an else statement.

Also, I have to use ES5 syntax because i'm working with ServiceNow and it doesn't allow for ES6.

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-use-foreach-with-an-array-of-objects-in-javascript
How to use forEach with an Array of Objects in JavaScript ? - GeeksforGeeks
June 10, 2024 - Using the forEach() method with an array of objects in JavaScript is essential for iterating over collections and performing operations on each object.