The replacer argument of the JSON.stringify method doesn't seem to work properly when dealing with nested objects

My dilemma is sending a simplified version of an object to the server.

{
 "fullName": "Don Corleone",
 "actor": {
  "actorId": 2,
  "name": "Marlon",
  "surname": "Brando",
  "description": "Marlon Brando is widely considered the greatest movie actor of all time... ",
  "heroList": [],
  "photo": "C:\\projects\\files\\actor\\1532955376934.png"
 },
 "heroProfilePhoto": "data:image/png;base64,/9j/...
 "production": {
  "title": "The Godfather",
  "imdbRate": 9.2,
  "genre": "8",
  "releaseDate": "1972-03-23T21:00:00.000Z",
  "director": "Francis Ford Coppola",
  "writer": "Mari Puzo",
  "detail": "The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son."
 }
}"

I have two questions:

1) Is it possible to extract specific data using the replacer parameter in JSON.stringify() ?

 {
  "fullName": "Don Corleone",
  "actor": {
   "actorId": 2
   }
}"

2) Can I at least extract certain information using the replacer parameter of JSON.stringify()?

{
 "fullName": "Don Corleone",
 "actor": {
  "actorId": 2,
  "name": "Marlon",
  "surname": "Brando",
  "description": "Marlon Brando is widely considered the greatest movie actor of all time... ",
  "heroList": [],
  "photo": "C:\\projects\\files\\actor\\1532955376934.png"
 },
}"

When I use this syntax:

JSON.stringify(hero, ['fullName'])
Result -> "{"fullName":"Don Corleone"}"

However, with this line:

JSON.stringify(hero, ['fullName', 'actor'])
Result ->
"{"fullName":"Don Corleone","actor":{}}"

I am puzzled as to why the 'actor' property is empty.

Answer №1

When using JSON.stringify, it's important to include all the data you want returned. Just specifying 'actor' alone is not sufficient.

To achieve the desired result, use:

JSON.stringify(hero, ['fullName', 'actor', 'actorId'])

UPDATE

I conducted some experimentation to explore the scenario where actorId exists both within the actor object and the parent object. Here's what I discovered.

JSON.stringify() outputs both instances of actorId when present in both the actor object and the parent object. To customize this behavior, a more intricate function needs to be created and passed to JSON.stringify() as outlined here

Below are some examples:

var json = {
    key1: "Value for key1 in parent",
    key2: {
        key3: "Value for key3 in child",
        key4: "Value for key4 in child"
    },
    key4: "Value for key4 in parent"
}

var out1 = JSON.stringify(json, ['key1', 'key3'])
/*
out1 = {
    key1: "Value for key1 in parent"
} // No key3!
*/


var out2 = JSON.stringify(json, ['key1', 'key2', 'key3'])
/*
out2 = {
    key1: "Value for key1 in parent",
    key2: {
        key3: "Value for key3 in child"
    }
}
*/

var out3 = JSON.stringify(json, ['key1', 'key2', 'key3', 'key4'])
/*
out3 = {
    key1: "Value for key1 in parent",
    key2: {
        key3: "Value for key3 in child",
        key4: "Value for key4 in child" // Both key4 returned
    },
    key4: "Value for key4 in parent" // Both key4 returned
}
*/

Answer №2

Utilizing Spread in object literals can greatly simplify our code

Consider constructing the Object in this manner:

const obj = {yourObj.fullname, yourObj.actor}
const yourAnswer = JSON.stringify(obj)

For further information, you may visit Spread_syntax

Given that JSON.stringify can be inefficient with large objects, it is recommended to utilize the method outlined above

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

Leverage jsencrypt in Ionic 3

Struggling to hash passwords for login on my Ionic 3 app, I attempted using jsencrypt following a tutorial but encountered issues as I couldn't grasp how it works... Here's what I tried : npm install --save jsencrypt import { Component } from ...

What are the best practices for incorporating an ASP variable into Javascript code?

Trying to incorporate an ASP variable into JavaScript code, but encountering difficulties. How can this be achieved? Any suggestions? <% dim strMyString strMyString = "hello there" %> <HTML> <body> <%=strMyString%> ...

What could be the reason for the Javascript function failing to run?

I need assistance in executing a function called "send()" which includes an AJAX request. This function is located in ajax.js (included in the code snippet) The Ajax success updates the src attribute of my image. The function seems to be working correctly ...

Concealing functions within Accessors

I've recently started working on a website project utilizing the node.js/express stack and I am experimenting with developing in the functional programming style, which is quite new to me. One issue I encountered was related to the express method res. ...

An issue occurred with npm resulting in exit code 2. The error is as follows: Command was unsuccessful: node_modules/.bin/vsce package --no

Here is the specific error displayed in cmd: TS1323: Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'esnext', 'commonjs', 'amd', 'system', or 'umd'. E ...

When using Javascript, an error is being thrown when attempting to select a nested element, stating that it is not a function

I am facing a challenge in selecting an element within another element, specifically a button within a form. Typically, I would use jQuery to achieve this as shown below: element = $('#webform-client-form-1812 input[name="op"]'); However, due t ...

The inner HTML functionality in Angular 2 seems to be malfunctioning when dealing with HTML tags

I am facing an issue with an array that includes displayName with HTML tags: this.topicsList = [ {id: "173", name: "Discussion1", displayName: "Discussion1", status: 1}, {id: "174", name: "discussion123", displayName: "discussion123", status: 1}, {id: "19 ...

What should be placed in the viewRef: MapViewNativeComponentType parameter when utilizing React Native Maps in the current.fitToSuppliedMarkers function?

useEffect(() => { if(!origin || !destination) return; mapRef.current.fitToSuppliedMarkers(["origin", "destination"], { edgePadding: { top: 50, right: 50, bottom: 50, left: 50} }) }, [origin, destination]); I'm currently in t ...

Expand the scope of the javascript in your web application to cater

I am in the process of creating a web application that utilizes its own API to display content, and it is done through JavaScript using AJAX. In the past, when working with server-side processing (PHP), I used gettext for translation. However, I am now ...

A function designed to detect errors based on the parameters supplied as arguments

In order to ensure secure access to my restful API, I am looking to implement an authentication function called "access". I would like the function to have the following structure whenever a user interacts with the server: access(id , token ,function(err) ...

Expanding one type by utilizing it as an extension of another type

I am looking to create a custom object with predefined "base" properties, as well as additional properties. It is important for me to be able to export the type of this new object using the typeof keyword. I want to avoid having to define an interface for ...

What are the steps for implementing a equirectangular image in WebXR with three.js?

Currently, I am developing a web application with Three.js that requires the use of equirectangular images for panoramic tours. My goal is to incorporate a feature that allows users to switch between normal mode and VR mode similar to React360 and AFrame. ...

Is it possible to utilize a TypeScript type in conjunction with io-ts?

Currently, I am in the process of validating API responses with io-ts. In my TypeScript setup, I have already defined the following data structure: export type Group = { id: number; name: string; } Now, my objective is to incorporate this type into ...

An in-depth guide on implementing Highcharts.Tooltip functionality in a TypeScript environment

Currently, I am trying to implement a tooltip activation on click event in Highcharts by following an example from this URL: Highcharts - Show tooltip on points click instead mouseover. The challenge I'm facing is that I am using TypeScript and strugg ...

What is the proper way to implement v-model with Vuex in <select> elements?

I included a <select> element in my design: <select v-model="amount" required> <option value="10">10</option> <option value="20">20</option> <option value="25">25</o ...

What is causing the TypeError in Discord.js when trying to read the 'voice' property? Any help troubleshooting this issue would be greatly appreciated

Hey everyone, I'm having an issue with my play.js file that I obtained from a Source Bin. If anyone could provide some assistance, it would be greatly appreciated. const ytdl = require("ytdl-core"); const ytSearch = require("yt-search"); //Global que ...

The Angular @HostListener beforeunload Event is a powerful way to handle

I've implemented the following code snippet in my main app.component.ts file within my Angular 17 project: @HostListener("window:beforeunload", ["$event"]) onTabClose($event: BeforeUnloadEvent) { $event.preventDefault(); ...

Troubleshooting TypeScript errors related to ReactNode post-upgrade to Create React App v5

Since upgrading to Create React App version 5, I've been encountering errors like the one below: TS2786: 'OutsideClickHandler' cannot be used as a JSX component. Its instance type 'OutsideClickHandler' is not a valid JSX element. ...

Automatically fill in an input field with jQuery by using the value from another input field

I am currently working on a loan calculator and am trying to find a way to automatically populate an interest rate field based on the loan amount entered. Here is an example scenario: For amounts ranging from 0 to 100,000, the interest rate is 4.50 For ...

How to Override Certificate Expiry in JavaScript

Is there a way to bypass security for an expired certificate when making an Https post request in Javascript? I have been successful in doing this with C# and Java, but unsure about how to proceed in JavaScript. function post() { var xmlhttp; xmlhtt ...