Remove a JSON line with JavaScript

When my API fetches a Json response, it looks like this:

{
 "name": "API",
 "count": 30,
 "newdata": true,
 "lastrunstatus": "success",
 "thisversionstatus": "success",
 "thisversionrun": "Mon Sep 07 2015 20:31:07 GMT+0000 (UTC)",
 "results": {
 "collection1": [
  {
    "name": "Item1",
    "power": "210",
    "name": {
      "href": "http://picture.item42.com/item42.html",
      "text": "Hammer of god"
    },
    "desc": "Iron Hammer",
    "index": 1,
    "url": "http://picture.item42.com/"
  },
  {
    "name": "Item2",
    "power": "230",
    "name": {
      "href": "http://picture.item42.com/item43.html",
      "text": "Sword of god"
    },
    "desc": "Iron sword",
    "index": 1,
    "url": "http://picture.item43.com/"
  }
 ]
}

To modify the Json by removing the "url" line for each item and eliminating the "href" property within the name to have "name": "Hammer of god";

I attempted various methods like below code to achieve this transformation: Data contains the copied Json as shown above

function transform(data) {
var yourArray = data.results.collection1;
    var p = 0;
    var i = 0;
    var destArr=[];
        var srcArr=yourArray;
        for(i in srcArr){ 
         if(srcArr[i].url) 
            destArr[p]=srcArr[i];
            p++;
      }
    srcArr=destArr;
  return srcArr;
}

Perhaps utilizing data.results.collection1.filter would be more effective? Currently, my code returns the modified Json without the header but retains the url row.

Answer №1

To clean up your json.data.list, iterate through each item and remove the link in the title and website:

for(entry in json.data.list) {
    delete json.data.list[entry].title.link;
    delete json.data.list[entry].website;
}

See Live Demo

Answer №2

To remove a property from a JSON object, simply use the delete keyword.

let myJson = JSON.parse('your json data');
delete myJson.propertyNameToDelete;

Answer №3

let jsonData = document.getElementById('json-data').value;
let dataObj = JSON.parse(jsonData);

dataObj.results.collection1.forEach(function(dataEntry) {
    delete dataEntry.url;
    delete dataEntry.name.href;
});

document.getElementById('output-result').value = JSON.stringify(dataObj);

JS Code Example

Answer №4

To accomplish your goal, it is recommended to utilize the JSON delete method in the following manner: Assuming that data represents your JSON object:

data.results.collection1.forEach(function(item) {
   delete item.url
   delete item.name.href
});

If you need to process multiple collections, a second forEach loop can be used.

Answer №5

Give this a shot:

Modify jsonData by removing the 'url' key and updating the 'name' value to be equal to obj.name.text in each object present in jsonData's results collection1. Lastly, log the updated jsonData into the console.

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

Issue with Sails.JS: Difficulty in retrieving associations using findOne method

I have a function that searches for a resource using its geographical coordinates. However, when using the findOne method, the comments collection from the model is not returned. Interestingly, if I utilize the blueprint route to search based on ID, the co ...

How to identify the total number of keys within a JSON variable using Django's ListView

I need help returning the number of links contained in the allLinks JSON variable in my Link.html page. I am struggling to understand how to use get_context_data() properly and pass the total count of links for each Post into context['CountLink'] ...

Angularfire2: Access Denied Error When User Logs Out

When utilizing the following method: login() { this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()) .then(() => { this.router.navigate(['']); }); } An error occurs during logout: zone.js:915 Unca ...

Tips for determining the full width of a webpage, not solely the width of the window

While we can easily determine the width of the window using $(window).width(); This only gives us the width of the window itself, not accounting for any overflowing content. When I refer to overflowing, I mean elements that extend beyond the visible view ...

What is the best way to extract the last JSON object from a JSONArray based on a specified value

I am currently working with a JSONArray that looks like the following: [ { "id": 1, "firstName": "abc", "isActive": true }, { "id": 2, "firstName": "cde", "isActive": false }, { " ...

Understanding the reading of Java Class List in Vue Js

As a beginner in Front-end development, I am trying to figure out how I can use Vue.js to read a Java class List. Specifically, I have a Java class that includes a list of fruits and I want to be able to display this list on the UI using Vue.js: public c ...

Modifying the default value script to function across various rows

Utilizing a script called jquery.defaultvalue.js, I have added default text to various input fields on a form: <script type='text/javascript'> jQuery(function($) { $("#name, #email, #organisation, #position").defaultvalue("Name", "Emai ...

The solution for fixing contenteditable is as follows:

I am currently working on a script to clean up pasted text within a contenteditable div. While the script is functioning well for most part, I have noticed that in Firefox, line breaks get removed when the text is copied within or between the divs. Does ...

Ways to calculate the sum of multiple series in highcharts

By utilizing the Highcharts value-in-legend plugin available at http://www.highcharts.com/plugin-registry/single/10/Value-In-Legend, I have managed to partially implement a method for calculating a total value of multiple series. However, I am facing chall ...

linking a div within a navigation bar

I have implemented a template from bootstrap. Here is the navigation bar where you can find the about section. Inside it, there is a bootstrap button: <button type="button" class="btn btn-light">Light</button> When I click on this button, the ...

Attempting to retrieve information from JSON or JSONP through the utilization of the WOT API

Recently, I utilized the WOT (web of trust) API and encountered a response structured like this: process( { "www.google.com": { "target": "google.com", "0": [ 95, 84 ], "1": [ 95, 84 ], "2": [ 95, 84 ], "4" ...

Is there a way to update the value of a property using jQuery?

Is there a way to retrieve the "top" property value along with its inline CSS adjustment? <article class="stack" style="position: absolute; left: 741px; top: 1000px;"> </article> I'm looking to subtract 200px from the top value, in this ...

Using Vue.js to iterate over a list of items and accessing specific array objects by their unique identifier

My JSON array of objects has the following structure: https://i.sstatic.net/1IUVE.png When generating a <ul>, I need to fetch an ID from an API for each <li>: <ul> <li v-for="genre in movie.genre_ids"> {{ genre }} ...

Is there a way to access the initial element of the array within this variable assignment?

When utilizing the element id 10_food_select: var id = $(sel).attr("id").split("_"); An array is generated as follows: ["10", "food", "select"] The desired outcome is to have id = 10 (or whichever value is in the first element). This can be achieved l ...

Issue with scroll bar not being repositioned correctly after hiding modal

I have a modal that opens when clicking on a button. However, once the modal is open, I am seeing two scroll bars: One for the modal itself Another for the html/body To try and remove the extra scrollbar, I used the following code: if ($(".dialog-popup ...

Using Guzzle to Make a JSON POST Request in Laravel 5.7

I need help with my code. I am trying to create a new store in Geoserver. public function post_store(String $name) { $client = new Client(); $res = $client->request('POST', 'http://localhost:8080/geoserver/rest/workspaces/&a ...

Different Slide Library Fullpage.js

Is it feasible to have two sections with the same slide in fullpage.js? For example, if I'm currently on slide 1 of section 1 and then move to slide 2 of section 1, can section 2 automatically switch to slide 2 as well? I'm curious if this funct ...

Withdrawal of answer from AJAX request

Is there a way to create a function that specifically removes the response from an AJAX call that is added to the inner HTML of an ID? function remove_chat_response(name){ var name = name; $.ajax({ type: 'post', url: 'removechat.php ...

Encountered an issue while trying to update a ServiceWorker for scope - Received a HTTP error

I encountered a puzzling issue with my Vue PWA app, as our error logs are flooded with instances of a particular user experiencing an error that myself and another person cannot reproduce. Failed to update a ServiceWorker for scope ('https://myapp.com ...

Easily ajaxify your website without the need for hash or hashbang URLs

Currently enrolled in a web design course, I am eager to explore the world of ajax and how it can enhance our projects. Unfortunately, our instructor focuses solely on design and HTML, leaving us to figure out the more technical aspects on our own. If I m ...