I am currently analyzing a JSON file that contains deeply nested JavaScript Objects. My goal is to rearrange the data so that objects containing a specific field value are placed at the top of the list

Currently, I am parsing a JSON file which contains a map of JavaScript objects. For instance:

    { 
        offers : {
               "1":{"id":"1", "category":"a", "offerType":"LS"}, 
               "2":{"id":"2", "category":"a", "offerType":"EX"}, 
               "3":{"id":"3", "category":"a", "offerType":"EX"}, 
               "4":{"id":"4", "category":"a", "offerType":"LS"} 

        }
    }

After reading this JSON, I am storing it in local storage. My goal is to rearrange it so that offers with an offerType of "LS" appear at the top of my local storage object.

The motivation behind this is to ensure that when I showcase these offers on my website, those with an offerType of "LS" are displayed first. I am implementing this in Angular:

            let offers = data.offers;
                if (offers != null) {
                    for (var index in offers) {
                        var offer = offers[index];

                        if (offer != undefined) {
                            if (offer.offerType == 'LS'){ 
                                offersLS = [...offersLS, offer];
                            }

                        }
                    }
                    if (offersLS != null){
                        offersLS.forEach(offerLS => {
                           let key =  offerLS['id'];
                           listOffers = offers[key], listOffers;
                        });

                    }
                listOffers = listOffers, offers;
            }

listOffers is the final data that gets saved as my local storage object. I attempted to achieve this with: listOffers = [...offersLS, ...offers] but that approach saves it in my localStorage as an array, whereas I require a 'map' of these objects or an object of objects. I am unsure of the correct terminology.

Answer №1

It's important to note that attempting to sort an object directly might not yield the desired outcome, as objects are not inherently sortable. Consider using arrays for sorting purposes.

However, a workaround solution involves sorting the keys of the object and then reconstructing a new object based on this sorted order:

const data = {
    "1":{"id":"1", "category":"a", "offerType":"LS"},
    "2":{"id":"2", "category":"a", "offerType":"EX"},
    "3":{"id":"3", "category":"a", "offerType":"EX"},
    "4":{"id":"4", "category":"a", "offerType":"LS"}
};

let temp;

const sortedData = Object.keys(data)
    .sort((key1, key2) => {

        // define your sorting logic here

        temp = data[key1];

        return temp.offerType === 'LS' ? -1 : 1;
    })
    .reduce((acc, currentKey) => {
        acc[currentKey] = data[currentKey];
        return acc;
    }, {});

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

Choose datetime datepicker formatting in ng-pick

Currently, I am utilizing Angular and have incorporated the ng-pick-datetime npm. However, when attempting to adjust the format after selecting a date (dd/MM/yyyy), it consistently displays as (MM/dd/yyyy) instead. I am uncertain about how to rectify this ...

Rspec's include matcher is a useful tool for checking the presence of elements within Hash and String objects

Is there a way in Rspec to verify that all the fields in a Hash object : {"id"=>5392501, "owner"=>"cainlevy", "name"=>"photor", "url"=>"https://api.github.com/repos/cainlevy/photor", "description"=>"Photo Organizer (in Ruby)", "created_at"= ...

The push method is not functioning properly in Node.js following the conversion process

I am attempting to add new data to an Array using the push method. The initial array is obtained from a json file that has been read using fs.readFileSync, followed by converting the data into an object with the help of the JSON.parse() method. Here's ...

The TextView is not displaying the Android Json data retrieved from mysqli

Currently, I am conducting a basic test to display JSON data fetched from PHP MySQLi in a TextView. TextView mTxtDisplay; String url = "http://192.168.1.102/web_service/test.php/"; @Override protected void onCreate(Bundle savedInstanceState) { super ...

Utilize an external JavaScript function within a React and TypeScript document

I have encountered an issue in my React/Next.js/TypeScript file where I am trying to load the YouTube iframe API in my useEffect hook. Here is the code snippet: useEffect(() => { const tag = document.createElement('script'); tag.src = ...

Exploring the Concepts of Union and Intersection Types in Typescript

I am trying to wrap my head around Union and Intersection types in TypeScript, and I've come across a case that's puzzling me. You can check it out on this Playground Link interface A { a: number; } interface B{ b: boolean; } type Un ...

Having Difficulty Converting JavaScript Objects/JSON into PHP Arrays

This particular inquiry has no relation to the previously mentioned identical answer/question... In JavaScript, I am dealing with a substantial list of over 1,000 items displayed in this format... var plugins = [ { name: "Roundabout - Interac ...

Is it possible to populate the blank cells in the weekday columns for previous and following months in a mat-datepicker or mat-calendar's display?

In order to enhance user experience, I am designing a calendar that allows users to select dates. My goal is to populate the empty cells at the beginning of the first week with dates from the previous and next months. For this project, I am utilizing the ...

Encountering Issues with TypeScript Strict in Visual Studio Code Problems Panel

I have discovered that I can optimize my TypeScript compilation process by utilizing the --strict flag, which enhances type checking and more. Typically, I compile my TypeScript code directly from Visual Studio Code with a specific task that displays the c ...

Coordinating multiple API requests for optimal performance

I have a task where I need to retrieve data from two different API endpoints. Once both sets of data are fetched, I need to compare the information obtained from each source. I am familiar with fetching data from a single API endpoint and using a callback ...

Using node.js to make an HTTP request and parse JSON data with the

I am currently working on developing a web application using node.js that needs to interact with a PHP API. My goal is to request a JSON object from the PHP API, which I can then use in one of my .ejs templates. Below is the code snippet for my node.js im ...

Leveraging RadChart dynamically within your application, without relying on HTML

Currently, I am in the process of developing a cross-platform native mobile app for Android and iOS using NativeScript and Angular. The charting engine I am utilizing is RadChart from Telerik. However, I am facing a challenge as I want to use these charts ...

Simulating @Input data for an Angular component using Jest

As we transition our Jasmine tests to Jest in our Angular project, we are encountering issues when attempting to mock @Input values of components in the tests. Previously, in Jasmine, we would write code like this: @Component({ selector: 'app-messag ...

Can we find a solution to optimize this unique component and minimize redundant code?

Currently, I have a wrapper component that enhances the functionality of the MUI Tooltip component by automatically closing the tooltip when the surrounding table is scrolled. The existing code works fine, but I want to enhance its quality by removing du ...

Transforming a circular data structure into JSON format within Firebase

https://i.sstatic.net/BhQtp.png The data returned from firebase is causing an issue when I try to stringify it: JSON.stringify(data) // where data represents the returned object This results in the error: TypeError: Converting circular structure to JSON ...

Encountering KeyError while attempting to parse JSON with multiple layers of nested keys in Python

I'm currently developing a Python program to convert calls to a social media API into CSV format. However, I've encountered an issue related to a key in the hierarchy that has two keys above it. The error occurs when running the code with PyDev i ...

connect a column from a separate array in pdfmake

In my current project, I am looking to link the values of an array that is different from the one present in the initial two columns. Is this achievable? (The number of partialPrice values aligns with the number of code entries). Despite several attempts ...

.Net Core receives the method name instead of the parameter value passed by TypeScript

Can someone explain why the code is passing "getFullReport" as the eventId instead of the actual value while making its way to the .Net Core 3.1 side? Prior to the call, I double-checked with a console.log to ensure that eventId holds the correct ID I am ...

Typescript enables bidirectional control of Swiper

I attempted to use the two-way control slider example from Swiper documentation, but I encountered TypeScript errors that prevented it from working correctly. Is there a way to make it compatible with TypeScript? The specific errors I received were: TS23 ...

Issue with RouterLink functionality in Angular 6

While following a Brad Traversy tutorial on coding, I implemented the instructions exactly as given. Below is my 'app.module.ts' file. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/c ...