Removing the column name from a JSON return in C# involves using a variety of techniques

Below is a JSON output I have received :

[
    {
        positionCode: "POS1",
        positionName: "POSITION 1",
        positionDescription: "",
        parentPosition: "POS2",
    },
    {
        positionCode: "POS2",
        positionName: "POSITION 2",
        positionDescription: "",
        parentPosition: "POS3",
    }
]

This JSON data is the result of calling my Web API, which has the following structure :

return new JsonResult(query.Select(x => 
new { x.PositionCode, x.PositionName , x.PositionDescription , x.ParentPosition }).ToList());

However, I would like the output to look similar to this image : https://i.stack.imgur.com/9OUuX.png

What changes should I make in either my JavaScript code or C# Web API to achieve the desired outcome? Thank you!

Answer №1

Assuming your setup is similar to the following:

var dataList = new List<PositionClass>
{
    new PositionClass { PositionCode = "POS1", PositionName = "POSITION 1", PositionDescription = "", ParentPosition = "POS2" },
    new PositionClass {  PositionCode = "POS2", PositionName = "POSITION 2", PositionDescription = "", ParentPosition = "POS2" }
};

You have two choices available:

Manage it within your C# code

Since you already have linq, convert your List<T> into an array or strings like this:

dataList.Select(data => new[] {data.ParentPosition, data.PositionCode, data.PositionDescription, data.PositionName}).ToArray()

Manage it within your JavaScript code

const response = [{
    positionCode: "POS1",
    positionName: "POSITION 1",
    positionDescription: "",
    parentPosition: "POS2",
  },
  {
    positionCode: "POS2",
    positionName: "POSITION 2",
    positionDescription: "",
    parentPosition: "POS3",
  }
];

const reformatted = response.map(res => Object.values(res))

console.log(reformatted);

Answer №2

To achieve this, JavaScript's Object.values() function can be utilized.

var data = [{ positionCode: "POS1", positionName: "POSITION 1", positionDescription: "", parentPosition: "POS2", }, { positionCode: "POS2", positionName: "POSITION 2", positionDescription: "", parentPosition: "POS3", }]; 

var result = [];

data.forEach(item => {
  result.push(Object.values(item));
});

console.log(result);

Answer №3

When you need an array of string values instead of selecting an anonymous object with string properties, you can modify the code as shown below:

var result = query.Select(x => new string[] { x.PositionCode, x.PositionName, x.PositionDescription, x.ParentPosition }).ToList();
return new JsonResult(result);

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

Retrieving arguments of a specified function in PHP

Currently, I am constructing a documentation page for a PHP library. To begin, I delved into the method of fetching an array of defined functions from a PHP file, and this technique is functioning superbly within a directory traversal loop. My current obj ...

Place an element in relation to the vertical size of a div that includes written content

Currently, I am working on implementing a button with a popup that appears underneath it when the user hovers over it. The specific requirements for this setup are: The size of the button should not affect the size of the popup The popup should always be ...

There is a delay in updating ng-if/ng-hide in real time on the HTML page

Assistance needed for implementing a slight adjustment in AngularJS with TypeScript. The requirement is to change the text of a button for 3 seconds upon clicking, then revert back to its original text. Two HTML elements are created for this purpose, each ...

What steps should be taken to effectively integrate Amplify Authenticator, Vue2, and Vite?

Embarked on a fresh Vue2 project with Vite as the build tool. My aim is to enforce user login through Cognito using Amplify. However, when I execute npm run dev, I encounter the following issue: VITE v3.1.3 ready in 405 ms ➜ Local: http://127.0.0 ...

Is there a way to incorporate both max-width and min-width in a matchMedia query effectively?

I'm currently utilizing the matchMedia API in my JavaScript code to identify viewports, with the goal of reducing DOM manipulations. Instead of using display: none extensively, I am opting for a v-if directive from Vue to determine when elements are ...

Ways to retrieve a specific value from a JSON dataset

I currently have an Ajax live search script with multiple text inputs for searching products. The live search functionality works perfectly, but I have a query: If I decide to change the name of a product, how can I go back to the previous page and re-s ...

Custom JavaScript clock designed for the Lockscreen of jailbroken iPhones

I am struggling with getting my JavaScript code to display the time correctly on my HTML Lockscreen. After looking at a few examples, I noticed that others are using document.getElementById() instead of document.write() and pushing it to a div. I attempt ...

Using useState props in React Native navigation screens with React Navigation

I'm currently working on my first React Native app with react navigation after previously having a background in web react development. In the past, I typically used useState for managing state. For instance, rendering a list of components based on d ...

Struggling with updating state using splice method within an onClick event in React Hooks

CODE DEMO I'm facing an issue with my code snippet where it appears fine when I console.log it, but fails to set the state. The goal is to delete a box by using splice when clicked, however, something seems to be preventing it from working properly. ...

Develop a fresh button using either JavaScript or PHP

I have designed a mini cart (drop down) on my WordPress site with different styles for when there are products and when empty. To enhance the design, I have utilized CSS pseudo elements before and after to add content dynamically. Is it possible to includ ...

Utilizing JQueryMobile, JSON, and transferring data to a fresh webpage

Hi there, hope everyone is doing well and having a great time coding! I have a question regarding passing a URL rel to a new page for future use. Let me explain with an example instead of going on and on. Imagine you are on page "A" and you have a link t ...

Utilizing 'nestjs/jwt' for generating tokens with a unique secret tailored to each individual user

I'm currently in the process of generating a user token based on the user's secret during login. However, instead of utilizing a secret from the environment variables, my goal is to use a secret that is associated with a user object stored within ...

Unable to retrieve HTML code from a webpage using its URL address

Currently, I am trying to retrieve the HTML code of a specific webpage located at . My initial attempts using HttpClient were unsuccessful due to exceeding request processing time. It seems like this website may have anti-bot protection in place. I attempt ...

Why am I unable to make a selection in the dropdown menu?

Can anyone help me figure out why I am unable to select an option from the material ui library and display it in the state? Has anyone else encountered this issue? For a detailed code example, check here import React from "react"; import ReactDOM from " ...

What is the best way to update the color of a v-select component?

Currently utilizing Vuetify for my project <v-select id="makeMeBlue" dense outlined :items="form.values.urlTypes" label="Single or Multi URL" v-model="form.values.urlType" :rules="form.ru ...

Aggregate data by various categories and compute a total sum

I developed a recipe creation tool using Laravel 5.2. With this application, users can include ingredients in their recipes, sometimes duplicating ingredients depending on their use. Currently, I am working on a feature that enables users to generate a P ...

Exploring the implications of Content Security Policy in conjunction with mod_pagespeed evaluations

I am currently in the process of configuring CPS rules for my website. One issue I have encountered is that mod_pagespeeds often uses 'unsafe-eval' for scripts, which goes against my security settings. An example of code generated by mod_pagespee ...

Is It Possible to Use Separate Stylesheets for Different Web Browsers?

I have been trying to implement a JavaScript code that loads a specific stylesheet based on the user's browser. However, it seems like the code is not functioning correctly as none of the stylesheets are being displayed. I have meticulously reviewed t ...

I am having trouble establishing a connection to the JavaScript MQTT server

Error Encountered: WebSocket Error 12031 - The Server Connection Was Reset In order to subscribe to MQTT messages from the user interface, the code below is being utilized. A Mosquitto broker is currently running on my local machine, with the IP address s ...

Creating an array of objects sorted in alphabetical order

My task involves working with an array of objects that each have a name property: var myList = [{ name: 'Apple' }, { name: 'Nervousness', }, { name: 'Dry' }, { name: 'Assign' }, { name: 'Date' }] ...