Guide to altering JSON using Javascript

https://github.com/smelukov/loftschool-example i am currently working on my project in this environment.

I have created a friends.json file in the main folder.

friends.json

    {
        "name": "John",
        "lastName": "Doe",
        "value": "5.24"
    },
    {
        "name": "Jane",
        "lastName": "Smith",
        "value": "6.00"
    },
    {
        "name": "Alice",
        "lastName": "Johnson",
        "value": "4.54"
    }
]

index.hbs

<div id="prev-results"></div>

<button id="loadButton">Load Results</button>

index.js

const loadButton = document.querySelector("#loadButton");
const result = document.querySelector('#prev-results');
 
loadButton.addEventListener('click', () => {
    fetch('friends.json')
        .then(response => {
            if (response.status >= 400){
              return Promise.reject();
            }

            return response.json();
        })
        .then(friends => {
                result.innerHTML = '';
                for (let friend of friends) {
                    const friendNode = createFriendNode(friend);
                

                    
                    result.appendChild(friendNode);

                }
        })
        .catch(() => console.error('Something went wrong'));
});
 
function createFriendNode(friend) {
    const div = document.createElement('div');
    
    
    div.classList.add('friend');
    div.textContent = `${friend.name} ${friend.lastName}`;

    const result = document.createElement("a");
    result.textContent = `${friend.value}`;
    result.classList.add("result");

    const label = document.createElement("a");
    label.classList.add("result-label")
    label.textContent = "mL/min/1.73m²";

    div.appendChild(result);
    div.appendChild(label);
    return div;
}

Now that I can retrieve objects from friends.json and display them on the webpage, how can I programmatically modify the contents of friends.json using JavaScript?

Answer №1

In scenarios where the client is unable to write back to the static file it receives, a database comes into play. For managing JSON-like document object stores that need manipulation capabilities, one possible solution is utilizing a platform such as MongoDB.

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

Automatically load file and play audio when the page is loaded

I have created code that allows me to input an mp3 file, output the audio, and display a visual representation of the music. Currently, loading the file is done manually through an input type="file". Now, I want to change it so that the music automaticall ...

Having difficulty arranging the material ui components in a left-to-right alignment

Hello, I need assistance with my bilingual website that supports English and Arabic. I am looking to align the MUI text fields and dropdowns in a right-to-left direction. The labels of the text fields and dropdowns are not styled properly. Currently, I am ...

What is the best way to change data into an array using Java script?

In this code snippet, I am utilizing a loop to send data to an ajax function in JSON format: foreach($careers->getItems() as $item){ if($item->getDepartment()==$departmentID && $item->getLocation()==$location ...

Handling dynamic routes with React Router 4 and the 404 path

I have been working with the latest version of React Router (4) and have implemented a dynamic route configuration as described in the tutorial. The routes are functioning correctly, except for when I tried to add a 404 path following the tutorial's i ...

What would be the most efficient method in Angular for saving and retrieving information on whether a user has previously selected a checkbox?

I am currently in the process of learning angular as I develop a web application that resembles a todo list, specifically focused on football teams. In this application, users can navigate through a menu to select a league from four options. The applicatio ...

Looking to access data efficiently with a Ruby on Rails API and client application. What's the best way

My Ruby on Rails API app is returning data in JSON format, and I have a client app also built with Ruby on Rails that needs to access this data. I am struggling to figure out how to retrieve the data from the API so that I can display it on the client app& ...

Trying to call the Wia class constructor without using the 'new' keyword will result in a TypeError

I'm having trouble running my code from a JSON file, as it's throwing this error message at me: TypeError: Class constructor Wia cannot be invoked without 'new'at Object. (/home/pi/wia-pi-camera/run-camera.js:3:25) 'use strict&apos ...

Google Interview Challenge: Finding Pairs that Sum Up

My approach to solving this problem involved iterating through the array and checking if there exists an item such that the sum equals array[i] + item. If such a pair is found, I return true; otherwise, I return false. Now, my main inquiry is: How can I m ...

Accessing a JSON file over a network using JavaScript

Struggling to access a basic data file using JavaScript, and it's proving to be quite challenging. The file will be hosted on a remote server and ideally accessed via HTTP. While I'm new to JavaScript, I've come across JSONP as a potential s ...

Using Python to analyze large JSON files with Markov chains

When working in Python, I utilize makovify to construct Markov models from extensive textual data in order to create random sentences. Additionally, I leverage nltk to ensure that the Markov models adhere to sentence structure. Due to the time-consuming pr ...

When trying to implement a dark/light theme, CSS variables may not function properly on the body tag

Currently, I am in the process of developing two themes (light and dark) for my React website. I have defined color variables for each theme in the main CSS file as shown below: #light{ --color-bg: #4e4f50; --color-bg-variant: #746c70; --color-primary: #e2 ...

What could be the reason for my onChange event not functioning properly?

The issue I'm experiencing involves my onchange event not properly copying the text from the current span to the hidden field. Any ideas on why this might be happening? Check out my code at this link. ...

Object attributes influenced by the field's value

As I work on crafting a JSON schema for a potential file layout, consider the following structure: { "name": "My project", "debug": { "actions": [ { "type": "type 1", "options": { "option 1 for type 1": "my-project" ...

Navigating through the features of www.addthis.com is simple and straightforward

I am looking to integrate the addthis.com plugin into my website. Specifically, I want to pass my own data to the plugin when users click on the email link. This data should then be sent to the client. Is there a way to achieve this? ...

AngularJS provides users with the ability to access additional information by matching specific identification

Is there a simple way in Angular to display the label of an item from an array without looping through it? I have an array of color options: $scope.colors=[ {id:"0",label:"blue"}, {id:"1",label:"red"}, {id:"2",label:"green"} ] And my data object store ...

Need for input

I am working on organizing my routes in a separate file from app.js. The login route requires access to a Firebase instance. routes/auth.js var express = require('express'); var router = express.Router(); module.exports = function(firebase) { ...

The JavaScript function will only run after the user clicks the button twice

I attempted to create a button that toggles the visibility of a div element. Initially, I added the "onclick" event to the button and wrote this function: function showElement() { var element = document.querySelector('.blocks-fnd-div'); if ...

Shut down a pop-up overlay

I've been facing a challenge in implementing greasemonkey to automatically close a modal when the "x" button is clicked. Allow me to share with you the code snippet for the webpage: <div class="modal-header"> <button type="button" class="clo ...

User access has been denied for the MySQL query

I am facing an issue with connecting to the database index.php DbFunctions.php {"User message":false,"error":1,"success":0,"error_msg":"Error occurred in Registration","tag":"register"} <br /> <b>Warning</b>: mysql_query() [<a hr ...

Retrieve the desired element from an array when a button is clicked

When I click on the button, I need to update an object in an array. However, I am facing difficulties selecting the object that was clicked. For better readability, here is the link to my GitHub repository: https://github.com/Azciop/BernamontSteven_P7_V2 ...