Loop fails to collect all values from the array

I am attempting to create two consecutive loops that will iterate through an array of customers and extract all the fruits from each customer's list. I initially tried using nested for loops, but this only provided me with the first fruit from each customer rather than every individual fruit in the entire array.

var customers = [{
            "Name" : "John",
            "Items" :[
                {"Fruits" : "Apple"},{"Fruits" : "Orange"}]
            },{
                "Name" : "Sam",
            "Items" :[
                {"Fruits" : "Pear"},{"Fruits" : "Nuts"}]
            },{
                "Name" : "Eric",
            "Items" :[
                {"Fruits" : "Banana"},{"Fruits" : "Raisins"}]
            }];

for(i=0; i<=customers.length; i++){
    for(a=0; a<=customers[i]["Items"].length; a++){
        alert(customers[i]["Items"][a]);
    }
}

Answer №1

Make sure to update your second for-loop to iterate over the items array instead of the customers array

for(i=0; i < customers.length; i++) //ensure i < instead of i <=
{
   for(a=0; a < customers[i].Items.length; a++) //note the change here
   {
     alert( customers[i].Items[a].Fruits ); // 
   }
}

A more precise way would be utilizing the reduce method

var allFruits = customers.reduce( ( a, b ) => a.concat( b.Items.map( s => s.Fruits ) ) , []);

Answer №2

Your first loop is functioning incorrectly. Please refer to the modified code below:

var clients = [{
            "Name" : "Alice",
            "Products" :[{"Vegetables" : "Carrot"},{"Fruits" : "Apple"}]
        },{
            "Name" : "Bob",
            "Products" :[{"Vegetables" : "Broccoli"},{"Fruits" : "Orange"}]
        },{
            "Name" : "Charlie",
            "Products" :[{"Vegetables" : "Spinach"},{"Fruits" : "Strawberry"}]
        }];
for(j=0; j<clients.length; j++){
    for(b=0; b<clients[j]["Products"].length; b++){
        alert(clients[j]["Products"][b]);
    }
}

Answer №3

Here is the solution to your problem.

const contacts = [{
            "Name" : "Alice",
            "Items" : [
                {"Fruits" : "Grapes"},{"Fruits" : "Mango"}]
            },{
                "Name" : "Bob",
            "Items" : [
                {"Fruits" : "Pineapple"},{"Fruits" : "Watermelon"}]
            },{
                "Name" : "Charlie",
            "Items" : [
                {"Fruits" : "Kiwi"},{"Fruits" : "Cherry"}]
            }];
 for(let i=0; i<contacts.length; i++){
 for(let a=0; a<contacts[i]["Items"].length; a++){
     console.log(contacts[i]["Items"][a]);
 }
}

Answer №4

To simplify the task, just utilize the concat method along with map and reduce.

let fruits = [].concat(...customers.map(a => a.Items.map(b=>b.Fruits)));

var customers = [{ "Name" : "John", "Items" :[ {"Fruits" : "Apple"},{"Fruits" : "Orange"}] },{ "Name" : "Sam", "Items" :[ {"Fruits" : "Pear"},{"Fruits" : "Nuts"}] },{ "Name" : "Eric", "Items" :[ {"Fruits" : "Banana"},{"Fruits" : "Raisins"}] }];

let fruits = [].concat(...customers.map(a => a.Items.map(b=>b.Fruits)));
console.log(fruits);

If the goal is to obtain all distinct fruits, consider using Set from ES6.

var customers = [{ "Name" : "John", "Items" :[ {"Fruits" : "Apple"},{"Fruits" : "Orange"}] },{ "Name" : "Sam", "Items" :[ {"Fruits" : "Pear"},{"Fruits" : "Nuts"}] },{ "Name" : "Eric", "Items" :[ {"Fruits" : "Banana"},{"Fruits" : "Raisins"}] }];
let fruits = [...new Set([].concat(...customers.map(a => a.Items.map(b=>b.Fruits)))];
console.log(fruits);

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

Retrieve and store an array from a JSON response using jQuery

Appreciate the assistance in advance. I am currently working with a plugin that requires a JSON response to be formatted as an array instead of an object. Below is a snippet of the JSON response I am receiving: { "instruments": [ { ...

I'm feeling lost trying to comprehend the operations of a two-dimensional array pointer

As a beginner to pointers, I've been encountering some challenges in understanding how they work. After looking for solutions on this page, I wasn't entirely satisfied with the answers provided. That's why I decided to conduct my own invest ...

Fire css animations only upon the addition of a specific class

By clicking on button 2, you will witness the animation effect in action. But, if another function alters the button, like checking a checkbox to show or hide it, the animation triggers again as if the button were clicked once more. How can I prevent the ...

Adding elements to an array appears to cause the previously created object to react

I am encountering a situation where once I add an object to an array, it becomes reactive to any changes made. // actions.js export const addToCart = ({ commit }) => { commit('addToCart'); // successfully updates the state setTimeout ...

Message from Discord: Unable to access the property 'MessageEmbed' because it is undefined

Attempting to create a simple welcome message embed. Here is my main.js file without the login token: const Discord = require('discord.js'); const client = new Discord.Client(); const MessageEmbed = new Discord.MessageEmbed(); const prefix = &ap ...

The 404 error message "object not found" is commonly encountered at the end of

Whenever I try to access this PHP page on my localhost using XAMPP Apache Server, I always get redirected to a "404 object not found" screen. Despite trying to output text with the echo command, I am still unable to see any results. It's frustrating b ...

The download handler (php code) is being triggered multiple times within a single request

My PHP script is responsible for handling download requests. Clients can access this script using a GET request, as shown in the Javascript example below: if (true) { window.open('/download?mode=paper&fid=' + fid, '_blank'); re ...

what is the best way to ensure the execution of requests within async.each in nodejs?

I am facing an issue with my code that uses async.each to iterate through an array and execute a function called "check" for each element. The check function contains a request, but when I run the code, I find that Node.js is not executing the check functi ...

Integrate my API with HTML using J.Query/Ajax technology

Finally, after much effort, I have successfully created a JSON java API. My API design is simple and based on Interstellar movie details: { "title": "Interstellar", "release": "2014-11-05", "vote": 8, "overview": "Interstellar chronicl ...

Is it possible to place a list/accordion above a button in Semantic UI?

Check out this rough code sandbox here There seems to be an issue with the accordion overflowing behind the button on the left side. I attempted to add style={{position: 'absolute', bottom:'2%', overflow: 'scroll'}} to the A ...

Unexpected behavior observed with D3 line chart zoom functionality

I'm struggling with implementing zoom functionality on a multi-line D3 chart. Whenever I try to zoom, the specific data point I want to focus on at an xy location is not properly targeted. Here's a snippet of the code I've been working on: l ...

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

What is the best way to save a reference using a POST API in NodeJs?

Currently utilizing the express.js framework for building a MERN stack application. This is my first endeavor into creating a full-stack JavaScript app, so a lot of the functions are new to me. I am in the process of sending a new post to a topic and updat ...

Verify if the link includes https:// while using angularjs

In my angular app, there is a lot of data stored in JSON format. [ {"link": "https://stackoverflow.com"}, {"link": "https://stackoverflow.com"}, {"link": "id-aW783D"}, //This data is incorrect {"link": "https://stackoverflow.com"} ] However, the ...

What is the proper method to call an async function as the main function?

I have a series of nodejs scripts that are designed to complete a task and terminate, rather than run continuously. These scripts utilize async functions, like the example below: const mysql = require('mysql2/promise'); ... async function main ...

Styling a CSS property using React

I’m having trouble figuring out how to properly format the marginLeft value in my code. I’ve tried various methods, but haven’t been successful yet. Can someone please provide assistance on escaping the dash when defining properties this way? If it ...

jQuery - selecting child elements with a strict hierachy restrictions

Can you provide the equivalent jQuery selector if I have a variable $table that references $('table.special') to start with? (something like $table.(...) but matching the original selector $('table.special > thead > tr')) Note: ...

Building Dynamic Forms with React.js and Bootstrap for Easy Input Field Management

In the process of developing a web application using React.js and react-bootstrap, I encountered an interesting challenge. On one of the form pages, users should be able to input symptoms of an illness they are dealing with. The key functionality required ...

"Unexpectedly, the original values of an array were altered by a Javascript

After creating a constructor function to generate an object, I set up an array named arr1 with initial values. Next, I use the map function on arr1 to create a new array called arr2. However, I noticed that the original arr1 was altered. Could this be du ...

Angular Singleton Service for Asynchronous UI-Router Operations

I've been using UI-Router for my Angular application. The data I fetch through an asynchronous $http call helps in creating a connection object, which I want to make available as a singleton. My aim is to prevent potential timing issues that may arise ...