Organize nested level components in react native into a more structured order

Currently, I am working with some JSON data that has the following structure:

const data = {
  "stores": [
    {
      "name": "s1",
      "id": "6fbyYnnqUwAEqMmci0cowU",
      "customers": [
        {
          "id": "4IhkvkCG9WWOykOG0SESWy",
          "name": "customer2",
        },
        {
          "id": "4IhkfikCG9WWOykOG0SESWy",
          "name": "customer1",
        },
        {
          "id": "9IfkvkCG9WWOykOG0SESWy",
          "name": "customer100",
        },
      ]
    },
    {
      "name": "s2",
      "id": "2D1fTgjAJ20ImiAqsWAEEI",
      "customers": [
        {
          "id": "3dfkvkCG9WWOykOG0SESWy",
          "name": "customer9",
        },
      ]
    },
    {
      "name": "s3",
      "id": "6rxmPFzIHKQ0EOAGGkAwKg",
      "customers": [
        {
          "id": "7IfkvkCG9WWOykOG0SESWy",
          "name": "customer7",
        },
      ]
    }
  ]
}

My task is to organize this data by sorting the customers' names. Here's what I have tried so far:

const sortedData = data.stores.sort(function(c1, c2) {
   return c1.customers[0].name < c1.customers[0].name;
}).map(storeInfo => (
  // Need to do something else with sorted data
)

However, my current method doesn't seem to be effective because it doesn't handle nested levels properly. Any assistance on this matter would be greatly appreciated.

Desired Outcome: Arrange the list of customers in alphabetical order within each store and then sort them among all the stores as well.

Answer №1

Here is a solution I came up with in two steps. It may not be the most efficient, but it could be useful to you.

const sortedData = [];

// Organize customers for each store
for (var i = 0, len = data.stores.length; i < len; i++) {
    sortedData[i] = data.stores[i];
    sortedData[i]['customers'] = data.stores[i].customers.sort(function(c1, c2) {
        return c1.name > c2.name;
    });
}

// Sort stores based on first customer's name
sortedData.sort(function(c1, c2) {
    return c1.customers[0].name > c2.customers[0].name;
});

console.log(sortedData);

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

Encountered an error while running the `npx-create-react-app my-app` command in

When attempting to run 'npx create-react-app my-app', the following error message is displayed: 'npx' is not recognized as the name of a cmdlet, function, script file, or operable program. Double check the spelling and path included to ...

error in three.js occurs when attempting to load .obj files

I've been encountering issues with OBJ files that I've downloaded from the internet. All of these files render like this: View Obj File Pic I'm using the standard OBJLoader for rendering. var loader = new THREE.OBJLoader(); loader.load( ...

The Expo application that was released on Google Play has been converted to an Android build, but encounters a keystore error when attempting to upload it back to

Hey there, I recently encountered an issue with my Expo app on Google Play where the ads were not displaying properly. I initially built the app using eas build and Expo credentials, but when I tried to switch to "./gradlew app:bundleRelease" build, I ran ...

Is there a way to create a dynamic gallery using Magnific Popup that showcases both images and an iframe video together?

One way I am utilizing magnific popup is to set up an image gallery using the code snippet below: $('.main-content').magnificPopup({ delegate: '.gallery', // selecting child items to open in pop-up when clicked type: 'image&ap ...

Setting the state variable value asynchronously using AngularJS UI-If

Is it possible to limit access to the sidebar until the user has completed the login process? The sidebar is located outside the main ui-view section I am assuming that authenticated is a state variable <div ng-controller="MyController" ui-prevent-to ...

Tips for successfully passing a parameter to the --world-parameters or npm run command for it to be utilized by scripts within the package

Although there are similar questions already asked, I still have a specific scenario that I need help with: In the example I am working on, I am using this repository and I have a script block in my package.json as follows: I want to be able to pass a pa ...

Adding to the Year Column in MySQL

I currently have the following MySQL format: {"2017": {"1": {"payed": 0, "charge": 0}}} Previously, I successfully used this format to execute SQL queries (such as reading/updating payed and charge values). However, I am facing an issue when trying to ad ...

Is there a way to determine the size of an array without having to make another function call?

In the code snippet below, there are two classes: the main class and class1. The class1 contains a function called foo1() which iterates over an ArrayList<> and is called once in the main class. After calling this function, the size of the array is r ...

Using NodeJS and EJS to Display MySQL Query Results

I am currently working on a project where I need to display data retrieved from a MySQL query in an HTML table. However, when I attempt to do so, I encounter the following output: [object Object],[object Object],[object Object],[object Object],[object Obj ...

Stop the unnecessary reloading of Ajax data when navigating back using the browser's back button in Chrome and Internet Explorer

I am currently designing a website where the main page showcases the latest 10 blog entries. As I scroll down and approach the end of the last item on the screen, another set of 10 blog entries automatically load through infinite scrolling. If a user clic ...

Angular.js page failing to reflect changes following Firebase request completion

myApp.controller('RegistrationController', ['$scope', function($scope) { var auth = firebase.database().ref(); // console.log("auth::"+auth); $scope.login = function() { $scope.message = "Welcome " + $scope.user.ema ...

Sequelize cannot locate the specified column in the database

click here for image description I encountered an issue where a column was not recognized after migrating with sequelize-cli. Even though all the columns are defined in the migration file, this error keeps appearing. Additionally, when trying to create a ...

Dealing with empty content in Rails 4.1.9

I have been working on my controller in Rails 3.2 and have the following code: def signup ::MailchimpSignup.build(params) respond_to do |format| <---- Error is occurring here. format.json { head :no_content } end However, after upgr ...

Is there a way to combine two array fields into one new array?

I am facing a seemingly simple issue that I can't figure out. I want to extract and save two fields from an array named $data1 into a new array. [cat_id] => 1 [parent_id] => 0 [cat_left] => 1 [options] => 0 [name] => soccer [creator] = ...

Explore a JSON document containing a hierarchy of dictionaries

Here is an illustration to consider: { "items": { "PYGXGE": { "id": "a", "number": "1" }, "sbe7oa": { "id": "b", ...

Encountering an error message stating "Buffer is not defined" while working with gray-matter

Encountering an issue when trying to utilize gray-matter in Angular 9, the error message displayed is: ReferenceError: Buffer is not defined at Object.push../node_modules/gray-matter/lib/utils.js.exports.toBuffer (utils.js:32) at push../node_modul ...

Encountering a glitch while iterating through function results in failure after the initial modification

I am facing some errors with the script provided below: var sections = ["#general_info", "#address_records", "#employment_history", "#driver_experience", "#military_experience", "#eeo_survey", &qu ...

What is the best way to remove an active item from a Vue v-list?

When using Vuetify's v-list-item directive, I encountered an issue where the active prop cannot be removed once an item has been selected. Here is my approach so far: <v-list-item-group pb-6 color="primary" class="pb-3 text-left"> ...

JavaScript code that functions similarly to VLOOKUP, allowing you to map input values from one field to

As a beginner in HTML and JavaScript, I am trying to create a simple form that automatically populates a specific "Customer Code" when a "Customer Name" is selected from a dropdown list (similar to an Excel VLOOKUP). However, the examples I found on Stack ...

Determine the instance's name as a string in JavaScript

Currently, I am utilizing Three.js in combination with javascript. Upon running the following line of code: console.log(this.scene.children[1]) I receive the following output in the console within Chrome: https://i.stack.imgur.com/6LBPR.png Is there a w ...