Iterating through a collection of objects to save the key of each object in

My current issue involves receiving an object of objects from Firebase, but needing to adjust the default order of items. To achieve this, I have implemented the Lodash orderBy() method.

computed: {
  sortedLogs() {
    return orderBy(this.logs, 'date', 'desc')
  }
},

The dilemma now is that this method removes object keys, which are essential for managing delete requests.

Original

{
    MFVMHJHnbpr: {
        date: 1598270895
        side: 'l'
    },
    MFVMblsdfdPb: {
        date: 1598270825
        side: 'r'
    },
    MsxvblsdfdPb: {
        date: 1598271225
        side: 'l'
    },
}

After orderBy()

{
    0: {
        date: 1598270895
        side: 'l'
    },
    1: {
        date: 1598270825
        side: 'r'
    },
    2: {
        date: 1598271225
        side: 'l'
    },
}

Answer №1

If you prefer using plain JavaScript, it is possible to achieve the same outcome; however, keep in mind that if you rely on element order, you may need to convert the object into an array. It's worth noting that objects in JavaScript do not have a guaranteed order (refer to this explanation).

const data= {
    MFVMHJHnbpr: {
        date: 1598270895,
        side: 'l'
    },
    MFVMblsdfdPb: {
        date: 1598270825,
        side: 'r'
    },
    MsxvblsdfdPb: {
        date: 1598271225,
        side: 'l'
    }
};
const output = Object.entries(data).map(item => (item[1].key = item[0], item[1])).sort((a, b) => a.date - b.date);
console.log('Array:', output);

// Alternatively, creating a "sorted object" - no guarantee!

const sortedObj = output.reduce((acc, curr) => { let objCopy = {...curr}; delete objCopy.key; acc[curr.key] = objCopy; return acc; }, {});
console.log('Object:', sortedObj);

Answer №2

orderBy keeps the original object intact, allowing you to save a duplicate of this.logs for removal purposes. It is essential to remember to modify the sortedLogs after making changes to the initial data.

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

Comprehension of async/await and the concept of promises

I am currently developing in node.js version 18.2.0 and here is the snippet of code I am working on: async function res_asyncf(){ await setTimeout(r => {}, 1000); } const res_promise = new Promise(async r => { await setTimeout(r, 1000); }); asyn ...

Is it possible for me to save external CDN JavaScript files to my local system?

Normally, I would include scripts from other providers in my application like this: <script src="https://apis.google.com/js/api.js"></script> However, I am considering whether it is feasible to simply open the URL , and then copy and paste th ...

Tips on validating a dynamically generated form with angularjs

As I am dynamically creating a form and have implemented two-way binding, my next task is to implement validation. Key Requirements: If there is a value in a field (e.g. Name: Raja), and that value is edited using $watch or $dirty, we should be able to ...

The grid lines in d3 js are not aligned with the axes

My current project involves creating a multi-line chart using d3.js in React. However, I am encountering an issue with the alignment of gridlines in the plot. The problem seems to be random, as some graphs have aligned gridlines while others do not. The c ...

The initial spacing glitch on the text rotator in javascript

I am uncertain whether this falls under a CSS issue or a JavaScript problem. Currently, I have a JavaScript text rotator that cycles through various words in a sentence, replacing individual words to alter the message. While it operates flawlessly, there ...

Unresponsive jQuery dialog during Ajax request

Currently, I have the setup so that a dialog box pops up when an AJAX post is successful. The AJAX post itself is successful as the alert shows, but for some reason, the dialog box doesn't appear. I'm struggling to understand why this is happenin ...

Can the content of a URL be preloaded before it is displayed?

My goal is to create a functionality where, upon clicking on a preview div, it expands to the screen size, displaying a custom loader, and then loads the content of a new URL when it's ready. Is this task achievable? const Works = ({changed}) => ...

Loading images dynamically in ReactJS allows for a seamless and customized user experience

I've been trying to dynamically fetch images from my images folder based on data retrieved from the database. Despite searching through numerous resources, I'm still struggling to crack this issue. Check out my code snippet below: import sword fr ...

Is there a way to dynamically compute the height of rows in a VariableSizeList based on their index?

Is there a method to dynamically calculate the height of rows in React using the react-window library? Since it's uncertain whether all rows will have the same size, I find myself needing to utilize VariableSizeList. However, I'm wondering if the ...

Combining multiple IDs in jQuery using a variable

Please find below the code I have written: var $btnNone = $('#btn-none'); var $btn1234 = $('#btn-1, #btn-2, #btn-3, #btn-4'); // The following selector is functioning correctly var $btnReview1234None = $('#btn-1, #btn-2, #btn-3, ...

What is the best way to streamline the if statement in JavaScript?

Here is the given code snippet: public noArtistBeingEdited(): boolean { if (this.isFirstNameBeingEdited()) { return false; } if (this.isLastNameBeingEditable()) { return false; } return true; } What are some ways to ma ...

Make a diagonal border using CSS styling

Is it possible to create a slanted border like the one shown in this image (red line) using CSS/CSS3 or JavaScript? <div id="DIV_1"> <img src="/uploads/2016/01/logo.jpg" width="250px" id="IMG_2" alt='' /> <nav id="NAV_3"& ...

Using the `map()` method in React to filter elements based on their index and only running the filter if the index meets a certain

I have a list that needs to be iterated through based on its index. The filtering criteria are as follows: if index == 0 if index is above 0 and below half of the array's length if index is above half of the array's length The current code I&a ...

Vue/test-utils unit tests fail to function properly with components that utilize asynchronous setup

Trying to implement tests on a component that renders asynchronously has been quite challenging. I attempted to create a simple component with an async title, but the issue persists. Adding suspense around the component, as well as using await flushPromise ...

How can you assess the differences between two JSON files using JavaScript?

I am currently working with 2 JSON files containing data. One file represents an article with specific data parameters, while the other file contains a list of categories with its own set of data parameters. Within the article JSON file, there is an attri ...

Error: Incompatibility - The variable is not functioning properly in node.js or express.js

Upon encountering the error message "TypeError: undefined is not a function," I called a callback with parameters null, array_reply, and threadResults. It appears that this section of code is problematic, but I am uncertain why. Your assistance in resol ...

The declaration file for the module 'ga-gtag' was not found

I am currently in the process of updating my project from Universal Analytics to GA4, and I have encountered some challenges along the way. My main obstacle at the moment is installing the ga-gtag module so that I can send events using the new formatting f ...

Troubleshooting: Bootstrap 4 Flexbox demos failing to function

I am currently in the process of developing a basic Express webserver that serves a landing page constructed with bootstrap. However, I am encountering issues with getting any Flexbox examples to properly function. Displayed below is my landing page. Is t ...

"What is the proper way to implement the Increment Operator within the Ngoninit() function

When I try to use the increment operator within ngoninit() to change a variable's value, I encounter the following error from the compiler: error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or ...

Updating JavaScript files generated from TypeScript in IntelliJ; encountering issues with js not being refreshed

Struggling with a puzzling issue in IntelliJ related to the automatic deployment of changes while my server is running (specifically Spring Boot). I've made sure to enable the "Build project automatically" option in my IntelliJ settings. Whenever I ...