Preserving the object's identifier post-reverse filtering in AngularJS and JavaScript

This isn't specifically related to angularjs, but rather JavaScript. I borrowed a filter from the chat example of angularjs and firebase, and this is how it appears.

angular.module('myApp')
  .filter('reverse', function () {
    function toArray(list) {
      var k, out = [];
      if( list ) {
        if( angular.isArray(list) ) {
          out = list;
        }
        else if( typeof(list) === 'object' ) {
          for (k in list) {
            if (list.hasOwnProperty(k)) {
              out.push(list[k]);
            }
          }
        }
      }
        return out;
      }
      return function(items) {
        return toArray(items).slice().reverse();
      };
  });

The issue with this code is that it removes an essential part of the object - its key. I rely on this key to query for a single object.

In my template:

<div ng-repeat="(id, post) in posts | orderByPriority | reverse">
    <a href="posts/{{post.id}}">{{post.title}}</a>
</div>

I can't use the id in (id, post) because it's just the index of the reversed array (0,1,2,3...).

I attempted to add this into the reverse filter, but couldn't get it to work.

 for (k in list) {
     if (list.hasOwnProperty(k)) {
         list[k].id = k;            // this is the line I added.
         out.push(list[k]);
     }
 }

Answer №1

There are two options available to you: 1.

for (k in list) {
    if (list.hasOwnProperty(k)) {
        list[k].key = k;
        out.push(list[k]);
    }
}
<div ng-repeat="(id, post) in posts | orderByPriority | reverse">
    <a href="posts/{{post.key}}">{{post.title}}</a>
</div>

This is the same method that you attempted before. It worked well for me too. (remember to use post.key!!)

2. Alternatively, you could take a cleaner approach by maintaining the key / value structure of your post objects. You can create a new array out and store key / value pairs there.

for (k in list) {
    if (list.hasOwnProperty(k)) {
        var newObject = {};
        newObject[k] = list[k];
        out.push(newObject);
    }
}

I have not personally tested the second approach!

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

Transform object into distinct entities based on their individual key value pairs

Here is my unique combined entity: { "levelId-0":1, "level-0":"1", "levelpoints-0": 15, "levelId-1":2, "level-1":"2", "levelpoints-1": 15, "levelId-2":3, "level-2":"3", "levelpoints-2": 15, ...

An error popped up while using the fetch API due to an unexpected end of input

fetch('http://www.freegamesforyourwebsite.com/feeds/games/?tag=platform&limit=100&format=json', { method:'GET', mode:'no-cors', dataType: 'json', headers: { 'Accept': 'a ...

Using an AngularJS array with ng-repeat

As soon as a websocket message is received, the code below executes: connection.onmessage = function (eventInfo) { var onConnectionMessage = JSON.parse(eventInfo.data); if (onConnectionMessage.messageType === "newRequest") { getQuizRequests(); } } T ...

Tips for delaying a StateChangeStart event until the completion of a ui-router resolve operation

In my angular application, I have implemented authorization logic and ui-router to restrict unauthorized users from accessing certain states/views. The standard approach I follow is to listen for a stateChange event that triggers the authorization logic. E ...

Transmit JSON from PHP to an autocomplete feature and include a data attribute in the input field

[{ "id": "39", "name": "John Doe", "code": "060400000" }] $(document).on("input", ".autocomplete", function(event) { var name = $(this).prop('id').split('_').pop(); $(".autocomplete").autocomplete({ source: function(request, respo ...

Add small pieces of content to CKEditor

Is there a way to add "atomic" block content into CKEditor? For instance, I would like to add <h1>Test</h1> right after the letter "B" in the sentence <p>A B C</p>. Currently, when using CKEDITOR.currentInstance.insertHtml('&l ...

What's the deal with receiving [object Object] in my JavaScript JSON document?

When I use console.log(values), it returns "[object Object]" instead of logging the array as expected. This is the code snippet I'm working with: let values = { "coins": 0, "griffinFeathers": 0, "souvenir": 0, "cogs": 0, "cats": 0 ...

Using useRef to update the input value

I utilized the useRef hook from React to capture an element. When I use console.log(this.inputRef), I receive this output: <input aria-invalid="false" autocomplete="off" class="MuiInputBase-input-409 MuiInput-input-394" placeholder="Type ItemCode or ...

Protractor: A Guide to Right Clicking on a Specific Element

Is it possible to trigger a right-click event on a specific element using mouse simulation? I have attempted the following code, but the context menu does not appear: var testElem = $('#someElementId span'); return browser.actions().mouseMove(t ...

Surprising occurrences in Express.js

I have encountered an unexpected issue in my application. The code in my app.js file appears as follows: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(bodyParser.xml({ xmlParseOptions: { normalize: ...

Personalize the drop area in Filepond

Is there a way to customize the filepond droparea by adding custom HTML with placeholder images to guide users on what kind of images should be uploaded and allow multiple uploads? https://i.sstatic.net/VFGfJ.png I attempted to add placeholders in an abs ...

What is the process for storing an array in AdonisJs migrations?

Having trouble saving an array into a PostgreSQL database! 'use strict' const Schema = use('Schema'); class UsersSchema extends Schema { up () { this.create('users', (table) => { table.increments(); t ...

Looping through dates in a POST request using JavaScript/GAS - What's the best approach?

My task involves posting timesheet entries for the upcoming month into a system using an API. In order to do this, I require the following: User ID Assignable ID Dates (in the format YYYY-MMM-DD) Hours Initially, I obtained the user_id and assignable_id ...

Utilize Angular 6 [ngClass] to dynamically add a class composed of multiple variables through direct string concatenation within [ngClass]

Currently, I am working with Angular 6 and I have the following variables: var1 = 'my'; var2 = '-'; var3 = 'class'; I am trying to achieve something like this: <div [ngClass]='var1 + var2 + var3'></div> ...

Is there a way for me to incorporate the input parameter value passed to a JavaScript function into the popup that is being opened by the function itself?

I am not very proficient in PHP and JavaScript, and I'm facing an issue while trying to pass a value from a main page to a popup page that is defined within this main page. To provide more context: In my account.php page, there is a link like this: ...

Obtaining essential data while facing a redirect situation

I need to extract the og data from a specific URL: https://www.reddit.com/r/DunderMifflin/comments/6x62mz/just_michael_pouring_sugar_into_a_diet_coke/ Currently, I am using open-graph-scraper for this task. However, the issue I'm facing is that it i ...

What is the best way to use a computed property as a style value for a component in Vue.js?

My component's template includes the following HTML element: .grid-item(:style="{ width: columnWidth, backgroundColor: 'blue' }") I want to dynamically set the width of this element using a computed property: computed: { columnWidth () ...

Protractor - Issue with clicking on hidden element with "ng-click" attribute

I'm facing an issue with a specific element that I am unable to click using Protractor. Everything was working fine until a few days ago. Technical information: Chrome version: 47.0.2526.106 Protractor version: 2.0 Selenium version: 2.44 CSS &l ...

What techniques can be employed to create a fully operational web application using AngularJS?

I have taken on the challenge of understanding AngularJS by creating a webapp. Within my Eclipse environment, I am working with 4 files: main.js, index.html, view1.js, and view2.html. Currently, I can get index.html to load when Tomcat is running. Embedd ...

AngularJs input field with a dynamic ng-model for real-time data binding

Currently facing an issue with my static template on the render page. <form name="AddArticle" ng-submit="addArticle()" class="form add-article"> <input type="text" value="first" init-from-form ng-model="article.text[0]" /> <input typ ...