How to iterate through two objects simultaneously using a directive in Angular and Vue.js

I am facing a challenge with creating an Angular directive that can iterate over a data object and display its values along with the values of a second unrelated object with similar structure.

Currently, I am developing a translation app where the original language file is displayed in one column while the translated version is shown in the next. My goal is to loop through the original object and also showcase the corresponding translation whenever available. I want to avoid merging the two objects so that the two-way binding between the translation object and the DOM remains intact for easy saving.

This is a simplified version of what I aim to achieve:

Objects

var master: {
    face: {
        a: aaa,
        b: bbb,
        c: ccc,
        more: {
            d: ddd,
            e: eee
        }
    },
    magic: magic,
    test: test
}

var translation: {
    face: {
        c: cccc,
        more: {
            d: dddd
        }
    },
    test: testttt
}

DOM output

<ul>
    <li>
        face
        <ul>
            <li>
                <div>aaa</div>
                <div></div>
            </li>
            <li>
                <div>bbb</div>
                <div></div>
            </li>
            <li>
                <div>ccc</div>
                <div>cccc</div>
            </li>
            <li>
                more
                <ul>
                    <li>
                        <div>ddd</div>
                        <div>dddd</div>
                    </li>
                    <li>
                        <div>eee</div>
                        <div></div>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
    <li>
        <div>magic</div>
        <div></div>
    </li>
    <li>
        <div>test</div>
        <div>testttt</div>
    </li>
</ul>

Although this query pertains to Angular, I intend to implement it using vue.js since the Angular community is larger, and I believe concepts learned from Angular can be easily adapted to vue.js. I prefer not to use Angular itself as Vue offers me just the right functionality without the excess baggage of a full framework.

Example code showcasing vue.js rendering an object as a tree

Find the project repository here: https://github.com/jdwillemse/translation-utility

Answer №1

To iterate over key-value pairs in Angular, use

ng-repeat="(key, value) in master"

Then, to display the value based on the key:

{{translation[key]}}

This link explains the basics of key-value looping.

Here is an example building a tree in Angular

If you are using Vue.js, you can achieve this by nesting key-value loops inside each other as shown here:

<ul id="repeat-object">
  <li v-repeat="primitiveValues">{{$key}} : {{$value}}</li>
  <li v-repeat="objectValues">{{$key}} : {{msg}}</li>
</ul>

In Vue, I'm unsure if you can access data using [] notation in the DOM like in Angular. In Angular, you can use {{translation[$key]}} for such access.

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

What is the process of directing to another HTML page within the same Express controller script?

I am looking to switch the initial page (login page) to a second page (admin dashboard) from within the same controller in Express after a specific action has been taken. Here is the relevant code snippet from my controller file nimda.js: function handle ...

Initiate Child Event within Parent Component

Before switching tabs in the parent component, I want the child tab to validate itself. My idea is to pass the onActive event from the parent to its children, <ClientInfo/> and <Details/>. This will allow the children to validate themselves a ...

What is the best way to separate a JSON response into different sections based on the value of the name field?

Hello, I am currently making an API call to the Myfxbook API and receiving a JSON response with a large amount of data. Is it possible to break down this extensive response into multiple smaller parts based on the 'name' value? Here is a snippet ...

Trigger the errorPlacement function of the jQuery Validation Plugin on events like onfocusout, keyup, and click

Currently, I am utilizing the jquery validation plugin and aiming to utilize the errorPlacement function in order to include error messages to the fields title attribute and display only a ✘ next to the field. Everything works as intended when the form ...

Struggling with integrating PHP within a JavaScript AJAX function

Here's a button I have: <button id= $id onClick="popup($id)">button</button> I am attempting to use it with an ajax function <script> function popup(id){ alert(" "); document.write(" "); } </script> My goal is to execute P ...

What are the steps to troubleshooting using VS Code and Chrome browser with Webpack?

Can anyone provide guidance on how to debug webpack in VS Code with the Chrome browser? As a beginner in programming, I'm struggling because webpack minifies everything into one line which makes traditional debugging methods ineffective. I haven' ...

Vue emits events with an undefined return value

I recently came across a piece of code that allows users to download attachments. <template #link="{ item, rowdata }"> <attachment-link v-test-id="'attachment-link'" :inventory-id="item" ...

While troubleshooting the app, I encountered an error that says: "The property 'answers' cannot be read as it is undefined."

Everything was going smoothly with my app until it suddenly crashed, displaying the error message "Cannot read property 'answers' of undefined". Let's take a look at the specific piece of code causing the issue: function mapStateToProps({ ...

Obtaining information from AngularJS callback function in loopback: A comprehensive guide

I am trying to figure out how to retrieve the "good" array from an angular function. Here is the function I have in my Angular code: app.run(function($rootScope,Communications,$http,$filter) { $rootScope.getCommunication = function(object_type ...

Using Volley for making a string request

I am attempting to retrieve data for Crypto coins from . Coins.java public class coins extends AppCompatActivity { List<coinlist> coinList; ListView listView; TextView empty; DecimalFormat df = new DecimalFormat("###,###,###,###,###.##"); final Con ...

Search for a substring in JSON using Python

Currently, I am faced with the challenge of extracting two pieces of information from a lengthy JSON file using Python 2.7. The structure of the JSON data is as follows: { 'device': [ { 'serial': '00000000762c1d3c&apo ...

Internet Explorer does not return results when using AJAX during the onchange event (specifically for IE only

My code is functioning correctly on other browsers, however in IE it does not provide any result when I select the dropdown button. Instead, it changes and displays an empty result. This is my AJAX: $("#book").change(function(){ var DOMBULK = $(" ...

If the window width is less than the specified value, hide the DIV and replace it with a

I came across a discussion about hiding a div if the screen is narrower than 1024px, and I'm looking to implement something similar based on the quoted code below. Essentially, I want to hide one div (id="krug_wide") if the window width is less than 1 ...

What is the impact of a floated element on vertical spacing?

I have come across an article discussing the usage of CSS, but I am puzzled as to why image number four is not positioned below image number one. Instead, it appears below image number three. Can someone please explain this to me? Here is the HTML code sni ...

Issue with Node Webpack identifying the "Import" statement

I'm diving into the world of Node and Webpack, but I'm struggling with getting my project to compile properly. Every time I try to load it in the browser, I encounter the error message: Uncaught SyntaxError: Unexpected token import. Let me share ...

transforming JSON data into an array format on the fly

When I make a call to an endpoint in my C# code, it returns data structured like this: { "name":"test", "clients": { "client1": {"id": "1", "count": "41"}, "client2": {"name": "testName"}, "client3 ...

Is there a way to resolve the issue of receiving the Error: lexical error: invalid char in json text?

I am attempting to interact with an API using application/json in R, but when I run this code: data <- fromJSON(content(XXX, type = "text")) I encounter the following error: Error: lexical error: invalid char in json text. ...

Adjust properties based on screen size with server-side rendering compatibility

I'm currently using the alpha branch of material-ui@v5. At the moment, I have developed a custom Timeline component that functions like this: const CustomTimeline = () => { const mdDown = useMediaQuery(theme => theme.breakpoints.down("md")); ...

Identify all the CHECKBOX elements that are visible and not concealed

On my page, I have various checkboxes - some with hidden=true and others with hidden=false attributes. Despite trying to use a selector or jQuery to locate checkboxes with the hidden property, I am still facing some challenges. My goal is to differentiate ...

How about, "Enhance your website navigation with a sleek anchor

After many attempts to implement smooth scrolling on my Bootstrap project, I have tried numerous Youtube tutorials and Google search results without any success. The latest attempt I made was following this Stack Overflow post Smooth scrolling when clickin ...