C# - Implementing JavaScript Object manipulation in .NET Core

As I was browsing, I noticed many similar questions from years ago. Let's kick off this discussion with a simple JavaScript example showcasing how easy it is to modify, read, and write properties in objects using this language.

Take a look at the code snippet below:

const dynamicObject = {
  a: [1, 2],
  b: "String val",
  c: 10,
  d: { sa: 1, sb: null, sc: [1, 2, 3] }
};

// Adding new properties
const newProp = "e";
dynamicObject[newProp] = "New val";
dynamicObject.f = false;

dynamicObject["d"]["sd"] = null
dynamicObject["d"].se = null

// Modifying properties
const prop = 'a'
dynamicObject[prop].push(3)
dynamicObject.b += " ABCD"

// Modifying child properties of another property
dynamicObject.d.sb = ["New", "Array"]
dynamicObject.d["sa"] += 5

dynamicObject["d"]["sa"] += 5

// Reading properties
const propValue = dynamicObject[prop]
console.log(propValue)

const propValueString = dynamicObject.b
console.log(propValueString)

See the live results here

I attempted to replicate this method using C#:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        dynamic dynamicObject = new {
          a = new int[] {1, 2},
          b = "String val",
          c = 10,
          d = new { sa = 1, sb = "abv", sc = new int[] { 1, 2, 3 } }
        };

        var DO = (IDictionary<string, object>)dynamicObject;

        // Adding new properties
        const string newProp = "e";
        dynamicObject[newProp] = "New val";
        dynamicObject.f = false;

        dynamicObject["d"]["sd"] = null;
        dynamicObject["d"].se = null;

        // Modifying properties
        const string prop = "a";
        dynamicObject[prop].push(3);
        dynamicObject.b += " ABCD";

        // Modifying child properties of another property
        dynamicObject.d.sb = new string[] { "New", "Array" };
        dynamicObject.d["sa"] += 5;

        dynamicObject["d"]["sa"] += 5;

        // Reading properties
        object propValue = dynamicObject[prop];
        object propValueString = dynamicObject.b;

        string result = JsonConvert.SerializeObject(dynamicObject);

        Console.WriteLine(result);
    }
}

.Net Fiddle example here

However, it doesn't produce the expected output as we're dealing with a strongly typed language like C#. Let's not dwell on this difference for now.

Does C# offer any structures, objects, or libraries that make managing object manipulations as easy as in JS?

Answer â„–1

IMPORTANT:

I have created an enhanced version with some improvements: See Version 2


To enhance the interaction with Object/Dynamic/ExpandoObjects using C# Net Core, I developed my own Class.

VIEW THE CODE HERE

Below is the complete code:

namespace FW {
    public class Expando
    {
        public Expando(dynamic value)
        {
            expando = ToExpando(value);
        }

        public ExpandoObject root { get => expando; }

        private ExpandoObject expando { get; set; }

        private ExpandoObject ToExpando(dynamic dynamicObject)
        {
            if ((dynamicObject as object).GetType().Name == "ExpandoObject") return dynamicObject;

            if (!(dynamicObject as object).GetType().IsGenericType) throw new Exception("No generic type");

            ExpandoObject expando = new ExpandoObject();

            ((object)dynamicObject)
            .GetType()
                .GetProperties()
                .ToList()
                .ForEach(p => expando.fwAddProperty(p.Name, p.GetValue(dynamicObject) as object));

            return expando;
        }

        // More methods and properties here...

    }

    public static class extExpandoObject
    {
        // Extension methods for ExpandoObject

    }
}

This Code snippet provides an example of its implementation:

// Implementation Example

The generated JSON output is shown below:

{
   // JSON Output here...
}

Your feedback or comments on this approach are welcome!

Please note that sublevels in JSON are represented in a single array format.

  • To Write:
    dynamicObject["parent", "node"] = "New field";
  • To Read: dynamicObject["parent", "node"];

Additionally, the implementation requires the use of strings for property access.

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

How to prompt the browser to download a file with a specific name using node.js and express

I've created a node/express website as part of my university project. It allows users to search for a specific law ID, which then displays a table with various files in different formats and languages related to that ID. I am using the "http-proxy" mo ...

The audio event continues to trigger even after it has been removed using removeEventListener

In my React component, specifically handling an audio track with an HTML <audio> element, I have implemented the following lifecycle methods: componentDidMount() { const {track} = this.props; this.refs.audio.src = track.getTrackUrl(); _.each(t ...

When using RS256 with JWT, the private key will not be accepted

I've been attempting to generate a JWT using 'jsonwebtoken' with RS256. The keys were generated using the following command: ssh-keygen -t rsa -b 4096 -m PEM -f <filename> The private key output appears as follows: -----BEGIN RSA PRIV ...

Expanding circle with CSS borders on all edges

My goal is to create a background reveal effect using JavaScript by increasing the percentage. The effect should start from the center and expand outwards in all directions. Issue: The percentage increase currently affects only the bottom and not the top ...

One way to have a Spring RESTful API return JSON in its true format rather than as a string is by serializing the

Currently, I am developing a RESTful API using Spring. The API structure is such that it displays all objects of its corresponding type. You can access the API at the following link: The Data Transfer Object (DTO) for this API is as follows: public class ...

Utilizing jQuery Template to retrieve a specific field from a JSON file

$.getJSON('dat.js', function(i,data) { $( "#lessons" ).tmpl( data[1].title ).appendTo( "#result" ); }); This is my JSON file { "posts": [ { "title": "Learning about A ...

Phone-based Authentication with Ionic 2

In my current project, I am working on implementing Ionic 2 login functionality using phone number and password. The backend is being handled by Laravel 5.3 passport. While the login process works fine when tested with Postman, I encountered an error when ...

What method does jQuery 2.x use to distinguish one element from another in the .data() function?

Back in the days of jQuery 1.x, elements would be assigned a unique identifier known as a cache key, stored in the ele[jQuery.expando] property of a node set by a specific line of code. This caching mechanism has similarities with how Mootools handles its ...

What is the most effective way to use Javascript to update an image depending on the selected value in a dropdown

My JavaScript skills are limited, but I have successfully created a form with 4 drop-down selection boxes on the left side for users to choose from (State, Car, Year, Condition). After making their selections, users can click a 'calculate' butto ...

Print on the Console in a Vintage-Inspired Way

When it comes to writing on the Console, I need to display the message "Enter your User Name:" in a unique way. I've been using Console.WriteLine("Enter your..."); but I want the prompt to appear as if it's being typed, similar to how it's d ...

I need assistance in locating an error; the error message states that $ is not defined and an object is expected

Issue with $ not being defined, object expected.. I am trying to verify if all sets of radio buttons are checked when a button is clicked! Please help. <script type="text/javascript> $(document).on('click', 'form', function () { ...

Refresh choices for the user interface selection menu

I've successfully mastered the art of redefining options for Webix ui.richselect/ui.combo. The technique involves: richselect.getList().clearAll(); richselect.getList().parse(options_data) Now, I'm facing a challenge with changing options fo ...

The interconnectivity between ngAfterViewInit in Angular's LifeCycle and observables

enable.service.ts @Injectable({ providedIn: 'root' }) export class EnableService { isEnabled$ = from(this.client.init()).pipe( switchMap(() => this.client.getEnabled()), map(([enabled, isAdmin]) => ({enabled: true, isAdmin: fals ...

"Unlocking the JSON element with jQuery Ajax: A step-by-step guide

I am trying to pinpoint a specific element within my JSON data: { "taskMeta": "Some meta info", "tasksLib": [ { "task001": { "id":"1", "createDate":"01.02.17", "dueDate":"02.03.17", "au ...

Strategies for extracting targeted information from a view within a CouchDB record

I need to determine the count of buildings per city in my documents. In this particular document, one of the cities mentioned is Kentucky, with a total of 6 cities in the document. However, when I use doc._id, it returns the ID but when I use doc.city, it ...

Anticipated the start of an object but instead encountered a string at line 1, column

I seem to be encountering an issue with my code that utilizes the Gson library. Upon running, the following error is thrown: 5596-5596/be.appmax.ktsjjt E/AndroidRuntime﹕ FATAL EXCEPTION: main com.google.gson.JsonSyntaxException: java.lang.IllegalStateE ...

Nested routing in Nextjs is encountering issues when implemented with a specific file

I'm struggling with setting up routes in Next.js. When I create the path "/app/[locale]/admin/page.tsx," I can access http://url/admin/ without any issues. However, when I try to set up "/app/[locale]/admin/login.tsx," I encounter an error and cannot ...

Interactive web page with dynamic JQuery functionality and navigable page links

I am working on the project/index.html page <html> <head> <title>Index</title> <scripts...> </head> <body> Hello <div id="content"></div> <button id="page1" value="page1"/> <but ...

Error encountered while attempting to load the vue-sanitize plugin within a Vue.JS application

Hi everyone, I'm encountering a problem with a plugin in Vue that I'm hoping to get some help with. Specifically, I am trying to incorporate vue-sanitize (available here: https://www.npmjs.com/package/vue-sanitize) into my project, but I keep re ...

"Discover the process of retrieving a specific element from a JSON array within PL/SQL Oracle 12c

Querying a column in an Oracle 12c table that contains CLOB data, specifically in JSON format under the column name 'dynamic_fields'. The content of the column is structured as follows: { "App": 20187.7", "CTList": "[ {\"line ...