Removing a property from a JSON object when initiating an Ajax request in JavaScript

Looking for guidance on JavaScript and ajax as a beginner. I have a JSON with an output cell that I want to remove:

{
    "cells": [{
            "metadata": {
                "trusted": true,
                "collapsed": false
            },
            "cell_type": "code",
            "source": "print(\"hi\")",
            "execution_count": 1,
            "outputs": [{
                "output_type": "stream",
                "text": "hi\n",
                "name": "stdout"
            }]
        },
        {
            "metadata": {
                "trusted": true,
                "collapsed": true
            },
            "cell_type": "code",
            "source": "",
            "execution_count": null,
            "outputs": []
        }
    ],
    "metadata": {
        "kernelspec": {
            "name": "Python [Root]",
            "display_name": "Python [Root]",
            "language": "python"
        },
        "anaconda-cloud": {},
        "language_info": {
            "pygments_lexer": "ipython3",
            "version": "3.5.0",
            "codemirror_mode": {
                "version": 3,
                "name": "ipython"
            },
            "mimetype": "text/x-python",
            "file_extension": ".py",
            "name": "python",
            "nbconvert_exporter": "python"
        },
        "gist": {
            "id": "",
            "data": {
                "description": "Untitled5.ipynb",
                "public": true
            }
        }
    },
    "nbformat": 4,
    "nbformat_minor": 0
}

Here is my attempt at removing the outputs cell in the code snippet below:

"use strict";

function _objectWithoutProperties(obj, keys) { 
    var target = {}; 
    for (var i in obj) { 
        if (keys.indexOf(i) >= 0) continue; 
        if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; 
        target[i] = obj[i]; 
    } 
    return target; 
}
var outputs = data.cells;
var data_dup = _objectWithoutProperties(data, ["outputs"]);
var id_input = $('#gist_id');
var id = params.gist_it_personal_access_token !== '' ? id_input.val() : '';
var method = id ? 'PATCH' : 'POST';

// Attempting to post data without outputs key
$.ajax({
    url: 'https://api.github.com/gists' + (id ? '/' + id : ''),
    type: method,
    dataType: 'json',
    data: JSON.stringify(data_dup),
    beforeSend: add_auth_token,
    success: gist_success,
    error: gist_error,
    complete: complete_callback
});
};

Seeking help to figure out why this code doesn't work. Any advice on how to properly strip a specific key (like 'outputs') from an ajax call when posting it to a JSON file would be greatly appreciated.

Currently working on a gist extension for Jupyter notebooks where I need to remove output while posting to GitHub's Gist service.

Answer №1

def removeProperties(obj, key="outputs") { obj.cells.forEach(cell=>delete(cell[key])); }

Answer №2

When utilizing ES6, you have the ability to utilize this specific syntax in order to eliminate outputs:

{
  ...information,
  cells: information.cells.map(({ outputs, ...additionalProperties }) => additionalProperties),
}

Please keep in mind that information refers to your entire object.

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

The expression req.files consistently comes back as an empty [object]

I have been encountering an issue with saving uploaded files using their original names (with express-fileupload). Whenever I upload a file, it gets saved in the directory as [object Object]. Node: var express = require('express') var app = exp ...

Problems with Navbar rendering on multiple occasions

GENERAL INFO I've encountered an issue with the re-rendering of my sidemenu in Gatsby. Despite my efforts, I can't prevent the sidemenu from re-rendering and overriding the data that I set for it. const [activeParent, setActiveParent] = useState ...

Each styled component will yield the respective type definitions using (@types/styled-components)

Encountering a strange problem with styled-components in VSCode. Every component from styled-components is returning 'any'. https://i.sstatic.net/0kFJw.png https://i.sstatic.net/S20cS.png I had it working previously, but unsure when it stopped ...

Having trouble accessing dynamically generated elements using Selenium

I've been attempting to change the router's SSIDs using a Selenium script, but I'm encountering difficulty accessing any JS elements generated by the router page. I've tried various Expected Conditions and methods without success. Here ...

Include the HTTP header in a GET request for an HTML hyperlink

Within my HTML code, I am using an <a> tag that will trigger a 302 redirect when clicked. However, I need to incorporate some HTTP headers into this GET request. Is there a way to achieve this without including the headers in the href attribute? Tha ...

Eliminate unnecessary scrollbar from fancybox iframe

I am trying to display content in an iframe using Fancybox, but I am encountering an issue. Despite all the content being contained within the iframe, horizontal and vertical scroll bars are appearing. When inspecting the element in Firefox, I noticed th ...

Is there a way to include an image in a serialized file?

What is the method to include image_form into form in Django? form - form.serialize() image_form - image $('#id_submit').click(function(e) { e.preventDefault(); var form = $('form').serialize(); image_form = $("#id_image")[0].f ...

Exploring how to utilize optional URL parameters within Express.js

When using Express.js version 4.14, I implemented the following route: app.get('/show/:name/:surname?/:address?/:id/:phone?', function(req, res) { res.json({ name: req.params.name, surname: req.params.surname, address ...

The parameter value experiences an abrupt and immediate transformation

I recently created an electron app using Node.js and encountered a peculiar issue that I am unable to resolve: Below is the object that I passed as input: { lessons: [ name: "math", scores: [90, 96, 76], isEmpty: false ] } ...

What is the process for incorporating beforeAnimate and afterAnimate callbacks into a custom jQuery plugin?

Let's imagine I have developed a plugin: // creating the plugin (function($){ $.fn.myPlugIn = function(options){ defaults = { beforeAnimate : function(){}, afterAnimate : function(){} ...

Exploring Angular 2 Routing across multiple components

I am facing a situation where I have an app component with defined routes and a <router-outlet></router-outlet> set. Additionally, I also have a menu component where I want to set the [routerLink] using the same routes as the app component. How ...

Sending AJAX data by clicking a link in Laravel 5

I am new to working with ajax and Laravel 5 I am facing some issues with passing data when clicking on a link. Let me explain what I am trying to achieve. Here is my HTML code: //this is the div that I want to append with data for each <div id="warun ...

Learn how to effectively share an image using the Math.random function

Is there a way to display a random number of images on a webpage using JavaScript? Let's say we want to show X number of images, where X is a randomly generated number. For the sake of this example, let's set X to be 10. <input class="randomb ...

Is it considered safe to display the error message from an AJAX call for security reasons?

When I make my ajax calls, they usually follow this pattern: $.ajax({ type: 'POST', url: '/Controller/DoSomethingSpecial', contentType: 'application/json;', ...

Challenge with NodeJS, Angular Seed, Gulp, Jasmine, and Karma

Starting an Angular Seed project and everything was working fine. I managed to launch the Jasmine browser, but encountered issues with my specs not working. In an attempt to fix this, I added a karma.conf file, which unfortunately broke the Jasmine browser ...

Modifying input values in AngularJS/HTML

I'm encountering an issue with the ng-repeat function in AngularJS within my HTML code. The problem is that when I change the input with the ID 'add-price' in one cartproduct, it simultaneously changes in all other cartproducts as well. For ...

What causes the event parameter to be lost during recursion?

Below is the given code snippet: <html> <head> <meta charset="UTF-8"> <title>title...</title> <link type="text/css" rel="stylesheet" href="jquery-ui-1.10.4.custom.css" /> <script type="text/javascript" src="jq ...

`Issues encountered while converting PHP Array to JSON format`

I've been encountering difficulties converting a multidimensional PHP Array to JSON. While using json_encode, the result is null. I'm working on developing an orgChart where the data is extracted from a CSV file and stored in an array. The layou ...

Using ajax to call the Google Maps Api is proving to be ineffective

I am facing some issues with a website. On this particular webpage (), I am trying to display a Google map on the location page using an AJAX function. The getLocation.php file is being called by AJAX: <?php echo '<div id="map-canvas"></ ...

Tips for adjusting HighCharts layout with highcharts-vue integrations

I have a fairly simple component: <template> <div> <chart v-if="!loading" ref="priceGraph" constructor-type="stockChart" :options="chartData" ...