Display the two values of an object pair using ng-repeat in AngularJS

I have an array of objects structured like this:

myCtrl.siteNameLabels = myCtrl.actual.map(function (value, index) {
    return {
        actualSite: {
            actualSiteName : value,
            actualSiteData:  myCtrl.tableData[index]
        },
        pastSite: {
            pastSiteName : myCtrl.pastSiteNameLabels[index] + "_past",
            pastSiteData : myCtrl.tableDataPast[index]
        }
    }
})

The array contains pairs of sites (current and past), each with a shared name where the past site is identified by having "_past" at the end. Both current and past sites have associated data in the form of numeric arrays.

While every site has present data, not all sites have past data available.

The challenge lies in displaying this data in a table header as follows:

Site1 | Site1_past | Site2 | Site3 | Site3_past | Site4

If only present site data was present, it could easily be displayed using an ng-repeat. However, the task includes integrating the optional past site data alongside their corresponding present sites.

This code snippet demonstrates how to generate the display for present sites:

<thead>
    <tr>    
        <th ng-repeat="label in $ctrl.siteNameLabels">{{label.actual.actualSiteName}}</th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="rows in $ctrl.tableData[0] track by $index">
        <td>{{$ctrl.dateLabels[$index]}}</td>
        <td ng-repeat="label in $ctrl.actualSiteNameLabels">{{$ctrl.tableData[$index][$parent.$index]}}</td>
    </tr>
</tbody>

This would render the display as:

Site1 |  Site2 | Site3 | Site4

Do you have any suggestions on how to modify it to achieve the desired format?

Site1 | Site1_past | Site2 | Site3 | Site3_past | Site4

Answer №1

Here is a suggestion for saving site information:

    site: {
        currentSiteName : value,
        currentSiteData: myCtrl.tableData[index],
        previousSiteName: myCtrl.previousSiteNames[index] + "_previous",
        previousSiteData: myCtrl.tableDataPrevious[index]
    }

Fingers crossed that this does not impact any other features...

Answer №2

let siteList = [{ name: "Site1", pastName: "Site1_past" },
                 { name: "Site2" },
                 { name: "Site3", pastName: "Site3_past" },
                 { name: "Site4" },
                ];

let sitesFlatList = [];
siteList.forEach(function(site) {
    sitesFlatList.push(site.name);
    if (site.pastName) {
        sitesFlatList.push(site.pastName);
    };
});
console.log(sitesFlatList);   

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

MUI: Autocomplete cannot accept the provided value as it is invalid. There are no matching options for the input `""`

https://i.stack.imgur.com/KoQxk.png Whenever I input a value in the autocomplete component, an unresolved warning pops up... Here's how my input setup looks: <Autocomplete id="cboAdresse" sx={{ width: 100 + " ...

Transform nested entities into a single entity where any properties that are objects inherit from their parent as prototypes

Exploring a new concept. Consider an object like: T = { a: 2, b: 9, c: { a: 3, d: 6, e: { f: 12 } } } The goal is to modify it so that every value that is an object becomes the same object, with the parent object as prototy ...

What is the best way to send a JavaScript variable to Django using AJAX?

I am facing an issue while trying to pass an array in json format using ajax to my django views. Even though I receive a status of 200 indicating that the POST request has been successfully made, when I attempt to display the data passed in another templat ...

Making a POST request to a Next.js API route results in a 500 Internal Server Error being sent back

Check out the code in createComment.ts file, which serves as a Next.js api route: import type { NextApiRequest, NextApiResponse } from 'next' import sanityClient from "@sanity/client" const config = { dataset: process.env.NEXT_PUBLI ...

Should we pass <script> tags or unsanitized values to the Handlebars layout?

How can I pass values to handlebars that are not sanitized upon output? For instance, I want to ensure that when using the code res.render('index', {script: '<script src="bundle.js"></script>'}), it is not rendered as {{scri ...

Passing arguments with $emit - Vue

Here is a simple method to handle alerts using $emit. But when passing arguments, it seems like the event is not being triggered at all. The goal is to update the value of alert with the result. Listening for the event on mount: this.$eventHub.$on(' ...

The IP validation feature in the textbox is not performing as anticipated

My goal is to have a textbox that receives an IP address and validates it before submission. To achieve this, I've developed a JavaScript class called `validityCheck`. In my main Vue.js component, I aim to utilize this class to validate the input&apo ...

Mastering the art of utilizing v-if and v-for with nested objects in Vue.js

Struggling to display nested object content using v-for. I have a prop containing an object, but the div doesn't show when I use v-if="prop". Any help on how to resolve this issue would be greatly appreciated. Below is the syntax I'm currently us ...

Unable to retrieve the text enclosed between the:: before and after the:: marker

I attempted this using the XPATH finder in Chrome, and it highlighted the element. However, when running my Selenium script, I received the following error: Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: ...

Issue encountered when trying to retrieve a database variable from a mapReduce operation in MongoDB

Greetings! I am currently developing an application that utilizes a MongoDB database. Within this database, there exists a user collection where all user data is stored. The structure of a document in this collection is as follows: { "_id" : ObjectId( ...

Displaying components in Vue 2 using data from an ajax call

How can components retrieved from an ajax response be rendered? For instance, suppose I have registered a component called "Test" and within the ajax response I encounter: <p>dummy paragraph</p> <test></test> <!-- vue component ...

Discovering an npm module within an ember-cli addon component

I recently encountered an issue while using ember-browserify to locate npm modules in my ember-cli applications - it seems to not function properly for ember-cli addons. This leads me to wonder: Are there alternative methods for importing npm modules into ...

What is the best way to access data from this $scope in AngularJS?

Upon printing selecteditems to the console, this is the output: [{"model":"Lumia","brand":"Nokia","subModel":["Lumia 735 TS","Lumia 510"],"city":"Bangalore"}] I have stored it in $scope.details as follows: var selecteditems = $location.search().items ...

Get the package from a Lerna-managed monorepository using a git URL

Currently working on a project using yarn. The project has a dependency that is part of a larger monorepo managed by lerna. Despite the subpackage being updated, it has not been published yet and I require access to that unreleased code. Is there a method ...

AngularJS interprets expressions in the 'action' attribute

This afternoon I encountered a rather peculiar behavior with AngularJS. If "//" is present in an expression within the "action" attribute of a form, Angular will throw an interpolate error. Take a look at the code snippet below. When you run this code, t ...

Sending information to a Flask application using AJAX

Currently, I am working on transferring URLs from an extension to a Flask app. The extension is able to access the current URL of the website. I have set up an AJAX request to connect to Flask, and the connection is successful. However, when trying to send ...

Revamp your JavaScript code to trigger when the clock strikes bold!

Having trouble setting up JavaScript to automatically bold the next clock time. Any tips on rewriting the JavaScript? For instance, if it is currently 6:49, I want the next clock time of 7:32 to be automatically bolded. And when the time reaches 7:32, I wa ...

Tips for maintaining focus while tabbing in a contenteditable field?

Why does the table lose focus every time I press tab instead of inserting a white space? How can I change this so that pressing tab just inserts a regular tab space? ...

Ensuring Node.js backend JavaScript waits for completion of my bash script before proceeding

Running three bash commands through a Node.js code snippet. Here's a portion of the script: exec(str, function(error, stdout, stderr){ console.log('stdout:'+stdout); console.log('stderr:'+stderr); if(error!=null){ ...

Divide the sentence using unique symbols to break it into individual words, while also maintaining

Is there a way to split a sentence with special characters into words while keeping the spaces? For example: "la sílaba tónica es la penúltima".split(...regex...) to: ["la ", "sílaba ", "tónica ", "es ", "la ", "penúltima"] ↑ ...