Using an arrow function in Aurelia to read a json file

I've been exploring Aurelia and delved into tutorials on PluralSight and Egghead.io, but I'm still struggling to resolve my current issue.

In a JSON file named bob.json, there is a collection of objects related to Bob. Each object in the collection has an ID. My goal is to use arrow notation to retrieve an object based on its ID. Here's what I have attempted so far:

bob.json

[
    {
        "id": 1,
        "name": "eyes",
        "position": "head",
        "color": "blue"
    },
    {
        "id": 2,
        "name": "nose",
        "position": "head",
        "shape": "triangle"
    },
    {
        "id": 3,
        "name": "mouth",
        "position": "head",
        "chapped": true
    },
    [more body data here]
]

person.html

<template>
    <ul repeat.for="bodypart of bodyparts">
        <li>
            <a id="${bodypart.id}" href="javascript:void(0);" click.trigger="displayPart($event)">${bodypart.name}</a>
        </li>
    </ul>
</template>

person.js

import {inject} from "aurelia-framework";
import {BodyData} from "bodyData";

@inject(BodyData)
export class(bodyData) {
    constructor(bodyData){
        this.bodyData = bodyData;
    }

    activate(){
        return this.bodyData.getAll().then(bodyparts => this.bodyparts = bodyparts)
    }

    displayPart(e){
        this.bodyData.getBodyPart(e.target.id)...
    }
}

bodyData.js

import {inject} from "aurelia-framework";
import {httpClient} from "aurelia-http-client";

let baseUrl = "bob.json";

@inject(httpClient)
export class BodyData {
    constructor(httpClient){
        this.http = httpClient;
    }

    getAll(){
        return this.http.get(baseUrl).then(response => { return response.content });
    }

    getBodyPart(id){
        return this.http.get(baseUrl).then(response => {
            return response.content.filter(n => n.id == id);
        });
    }
}

The sections with ellipses are the areas where I am unsure about implementing the arrow function. My main questions revolve around understanding what should be placed in those spots to only return the object that matches the specific ID. Additionally, I am seeking guidance on resources explaining how to effectively utilize arrow notation with JSON data.

UPDATE:

After conducting some research, I came across a helpful explanation at:

From my understanding, arrow notation operates similarly to an SQL statement.

In the bodyData.js file, I utilized the following statement:

getBodyPart(id) {
    return this.http.get(baseUrl).then(response => {
        return response.content.filter(n => n.id == id);
    });
}

As per my interpretation, this filters the returned content based on the object's ID matching the passed-in ID. It bears resemblance to how an SQL query would read:

SELECT [object]
FROM [json file]
WHERE [object].id = id

If my understanding is correct, then I believe I have grasped that part. However, the aspect that is currently perplexing me is the displayPart(e) function within the person.js file. How can I verify whether this data retrieval process is yielding the correct value? Any assistance provided will be greatly appreciated.

Answer №1

AHA! I've finally cracked it! Let me try to contain my excitement, because although this may seem small to some, it's a major breakthrough for me. Here's the last piece of the puzzle. Following the update mentioned earlier, all subsequent steps need to be taken within the promises' THEN statement.

Now, in the person.js class, replace the displayPart(e) code with the following snippet:

displayPart(e){
    this.bodyData.getBodyPart(e.target.id).then(bp => {
        this.bp = bp;
        // Implement any additional code or functionality using this.bp to access the collection.
    });
}

This will retrieve a collection of objects that correspond to the ID provided. Success! Issue resolved. Hopefully, this solution will benefit someone in the future.

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

Transferring data between functional components in ReactJS and dealing with the output of [object Object] or undefined

I'm struggling with passing a prop in functional components that are both located in the same .js file. I previously attempted to seek help for this issue, but unfortunately, it wasn't productive. My goal is to extract the member_id from the GET ...

The Ajax request is not being triggered when using a different form submit method

Being a tech enthusiast, I have developed a handy function: function blur_slide_visit_count(){ $.ajax({ type: 'POST', url: 'add_save_slide_visitor_count.php', async: false, data: { fillvalue: fieldAr ...

use ajax to dynamically load a section of the webpage based on filter criteria

I need to implement a search filter using 3 checkboxes. The search results will be displayed in the div with the id=posts_results <div class="checkbox"> <label><input type="checkbox" id="id1" class="typePost" value="En groupe"> ...

How can I connect a gridview with JSON using the onClick event of a LinkButton within another gridview?

Currently, I am populating a Gridview with JSON data (first Gridview) that contains certain columns with Linkbuttons. I am looking to populate another gridview (second Gridview) with JSON data when the Linkbutton inside the first gridview is clicked. Can ...

Experiencing a problem with the JavaScript loading function

An error was logged in the console SyntaxError: unterminated string literal A piece of code is supposed to display a notification $(document).ready(function () { alertify.success("Success log message"); return false; }); Despite testing the cod ...

Angular button press

Recently, I started learning Angular and came across a challenge that I need help with. Here is the scenario: <button *ngIf="entryControlEnabled && !gateOpen" class="bottomButton red" (click)="openGate()">Open</button> <button *ngIf ...

The onChange function in React JS for a Material UI 'number' TextField retains the previous value

In this element, I have an onChange function: <TextField id="rowinput" type="number" defaultValue={this.defaultRows} // defaultRows = 1 inputProps={{ min: "1", max:"5"}} onChange= ...

Switch between showing the Font Awesome TitleText and its associated Class with a single click

Can the value of the title attribute for <i> be toggled? For example, if the title is set to <i title="Favorite This Post" class="fa fa-star-o" aria-hidden="true"> within <div class="postoption"> I would like to toggle both the title te ...

Struggling to access a JSON file using Angular framework

I'm currently working with the following JSON and controllers: JSON Format: {"tomcatLogDir":"C:\\apache-tomcat-7.0.70\\logs","tomcatLogs":["1.log","2.log","3.log"]} Factory: app.factory('filesFactory', [ '$http&a ...

Issue with React hook state persistence in recursive function

I implemented a recursion custom hook that utilizes a setTimeout function to provide 3 chances for an operation. Once the chances run out, the recursion should stop. However, I encountered an issue where the setTimeout function is not properly decrementin ...

Dynamic presentation created with Serif software

As a newcomer to web coding and one of the older generation, I recently created a basic .swf slideshow using Serif's graphic software. However, I realized that it does not display on an Apple iPad. You can experience this issue quickly here. My questi ...

The script aggregations in Elasticsearch are giving an error due to an unrecognized key for a START_OBJECT

My goal is to create a query that allows for multiple aggregations within a single request. Below is the query I am currently using: { "size": 1, "aggs": { "firmNames": { "terms": { "field": "firm_name", ...

Is it possible to use a full-width material-ui Button inside a Badge component?

Within a grid, I had initially used fullWidth on a Button to make it expand and fill the container. Everything was functioning correctly until I enclosed the Button in a Badge element. Now, the fullWidth property is not being applied, and the button rever ...

How to Convert a String to JSON in Python

I have data in this specific format: "{u'Status': u'Up About an hour', u'Created': 1468874455, u'Image': u'instavote/vote', u'Labels': {u'com.docker.compose.service': u'webapp&apos ...

Is the API providing a response in the form of an HTML document

I just created a cutting-edge React application that leverages the power of "fetch" to fetch data from an API. Within my App component in the "App.js" file, you can find the following code snippet: function fetchData() { fetch(`WORKINGURLWITHAPIKEY`) ...

Vue Filtering and Pagination Implementation

In Vue pagination, how can you control the number of array objects to be displayed based on a user-selected amount like 10, 15, or 25? I successfully implemented rendering 10 items per page and it's functioning smoothly. ...

script locate the div ID within a given text and clear its content

My string contains some dynamic HTML with a div element having an id of "time", Here's an example: myString = "<div class="class">blahblah</div><div id="time">1:44</div>" How can I generate a new string that is identical to ...

Merge the chosen values from the drop-down menu into one string

Any suggestions would be greatly appreciated! I am currently developing an application using ASP.NET web forms that consists of a dropdown list and two list boxes. I want these elements to be cloned whenever a specific button is clicked. However, my issue ...

Avoid nesting ternary expressions when possible - consider alternative solutions

I am currently working on a React component that has 4 different states: advisoryResults, results, noResults, and newAccount. While I initially thought about using a ternary expression for this, it turns out that it is not allowed in this case. Can you su ...

Tips for choosing a dynamically generated ajax element

Question for you: I have a snippet of HTML code that looks like this: <li class='entry'> <div class='entryContent'> <p class='entryText'>Entry text></p> <a href="#" c ...