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

A function in Jasmine for testing that returns a promise

I have implemented the following function: function getRepo(url) { var repos = {}; if (repos.hasOwnProperty(url)) { return repos[url]; } return $.get(url) .then(repoRetrieved) .fail(failureHandler); function ...

Adjust the position if the height exceeds 100 pixels

Can someone help with this code issue? $(document).ready(function () { if ($('.pi-img').height() > 100) { $(this).css('top' , '30%'); console.log('yeah'); } }); I am encountering difficu ...

Obtain Page Parameters within a Nested Next.js Layout using App Router

My Next.js App Router has a nested dynamic page structure using catchall routes configured like this: app/stay/ |__[...category] | |__page.js |__[uid] | |__page.js |__layout.js Within the 'layout.js' file, there is a con ...

Encountering an 'Uncaught TypeError' with Tumblr API due to undefined property 'type' not being read

I have multiple feeds on my website, each fetching posts from various tags. The first feed is functioning properly, but the 2nd and 3rd feeds are displaying the following error: Uncaught TypeError: Cannot read property 'type' of undefined All ...

Having trouble with AngularJS UI Router failing to load template and controller?

I am currently trying to identify the error in my code. Whenever I access /dashboard, it only loads the template from the first route, which is defined as SYSTEM_VARS.includes.general.root. However, it does display the console.log message inside the resolv ...

Unable to save data in local storage

I'm enhancing an existing chrome extension while ensuring a consistent style. I am looking to implement a new feature, and I have written a script that saves the user's selection from the popup and sets a new popup based on that choice going forw ...

Protractor - I am looking to optimize my IF ELSE statement for better dryness, if it is feasible

How can I optimize this code to follow the D.R.Y principle? If the id invite-user tag is visible in the user's profile, the user can request to play a game by clicking on it. Otherwise, a new random user will be selected until the id invite-user is di ...

Capturing numerous data points with JavaScript

<span> <label class="label">Color</label> <span class="foo"><input name="Color" value="Blue" class="customs" maxlength="100" type="text"/></span> </span> </span> <span> <label cla ...

Google script integrated with the Skyscanner Flights API

I am currently in the process of familiarizing myself with using the Skyscanner Flights API through Google Script. Unfortunately, most of the resources available online are quite complex for beginners like me. From what I understand, the steps to access f ...

Encountering a 404 error in a Next.js application while utilizing path parameters

Embarking on my journey into web development, I am trying to grasp the concept of server-side rendering using next.js and react within a lambda function. When running the code on a lambda, the result is somewhat functional as it displays the parameter valu ...

Analyzing two arrays and utilizing ng-style to highlight matching entries within the arrays

My list displays words queried from a database, allowing me to click on a word to add it to another list that I can save. This functionality enables me to create multiple word lists. My goal is to visually distinguish the words in my query list that have a ...

Display Rails view using JavaScript when clicked

I have a task to create a view where users can click on different buttons and see different content displayed based on the button they choose. I attempted to achieve this using JavaScript, but unfortunately, I couldn't get it to work as intended. Init ...

Issues have been identified with the functionality of the Am charts v3 XY in conjunction with a

I'm currently working on a project with angularJS and utilizing the npm package amcharts3 "^3.21.15". I've encountered a minor issue regarding the logarithmic scale in my XY chart. Below is my chart without the logarithmic scale: View working ch ...

What sort of JavaScript WYSIWYG text editor provides formula support?

Looking for a Javascript rich text editor that offers formula selection in the toolbar. Any recommendations? ...

Tips for maintaining a sticky header while continuing to utilize Bootstrap table classes such as table-responsive and table-stripped

This is Here's my code on jsfiddle I've attempted to make the header sticky while maintaining the current layout, but every approach I've tried ends up messing with the responsiveness of the table. My next plan involves using a JavaScript ...

Uncovering the inherent worth of an item pulled from a remote location using Vue.js

Currently, I am retrieving a list of countries by making an API call in VueX. The fetched data is then stored in a state using a mutation. Essentially, the countries are saved in a variable known as this.$state.getters.countryList, which can be accessed f ...

What is the best way to access a cached value?

I am currently utilizing the node-cache-manager library to manage caching in my Node.js application. After successfully adding an item to the cache using the following code: import cacheManager from 'cache-manager'; const memoryCache = cacheMan ...

The functionality of Jquery-chosen appears to be malfunctioning when applied to a select element

I am encountering an unusual issue with Jquery-Chosen. There is a multi-select box within a pop-up where the options are populated using an ajax call. Strangely, Jquery-Chosen does not seem to work on it. However, if I use a static multi-select box in the ...

Creating a dynamic path to an imported file in React: A step-by-step guide

Struggling with a dilemma regarding dynamically generated paths for importing files in React. I have utilized the map() function to generate a dynamic part of the code, consisting of a repetitive sequence of div elements, each housing an audio element. The ...

Express server experiencing a conflict with authentication sessions

Currently testing out a library found on this link and encountering a frustrating issue related to potential conflicts in cookie or header authentication. Upon logging into one account, everything runs smoothly. However, attempting to log into a different ...