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

Upload a binary file as a parameter in JSON format by utilizing multipart/form-data within a curl POST request

I've been searching extensively but haven't been able to find a solution to this particular problem. My goal is to include a binary file as a JSON parameter using multipart/form-data in a POST request with curl. I attempted the following, but it ...

In search of an efficient method to verify JSON input using the Play framework

While I find it easy to read and validate the expected fields in a JSON input, I struggle with properly handling an exception if an unexpected field is found. It would be helpful if the play framework could provide some guidance on this issue. I could manu ...

Turning an Array of Objects into a typical JavaScript Object

Below are arrays of numbers: var stats = [ [0, 200,400], [100, 300,900],[220, 400,1000],[300, 500,1500],[400, 800,1700],[600, 1200,1800],[800, 1600,3000] ]; I am seeking guidance on how to transform it into the JavaScript object format shown below. ...

Guide for accessing and interpreting a random folder arrangement using JavaScript located alongside index.html

I am currently developing a testing reporting tool that organizes images into folders, resulting in a structure similar to this: root/ /counter/ img1.png img2.png /alarm/ img3.png The names of the folders like counter and alarm are not f ...

How can I display and utilize the selected value from a Rails select form before submitting it?

Currently, I am in the process of developing a multi-step form for placing orders. This form includes two dropdown selectors - one for shipping countries and another for shipping services. Once a country is selected, all available shipping services for tha ...

Reveal concealed fields following the selection of a specific option

I'm looking to create a bookmarklet that will automatically fill in values when clicked. Currently, I can select values using: document.getElementById('component').value="IAE-Data Agent"; document.getElementById('component').onch ...

% unable to display on tooltip pie chart in highcharts angular js

https://i.stack.imgur.com/Ccd7h.png The % symbol isn't displaying correctly in the highcharts ageData = { chartConfig: { options: { chart: { type: 'pie', width: 275, height: 220, marginTop: 70 ...

Passing an array of selected values from Vue.js to a text area and adding them to the existing content

I'm facing a situation and I could really use some assistance. The image shows that there is a multiple select box on the left with numbers, and a text box on the right. My goal is to allow users to click on the house numbers in the select box and hav ...

Error in Chart.jsx: Unable to retrieve the length property of an undefined object in the COVID-19 Tracker App

INQUIRY Greetings, I am in need of assistance to identify an error that is perplexing me. The source of this code can be traced back to a tutorial on creating a covid tracker available on YouTube. While attempting to implement the chart feature, I encounte ...

Show a Toast in React without relying on useEffect to manage the state

I have successfully implemented the Toast functionality from react-bootstrap into my application using the provided code. However, I am unsure if it is necessary to utilize useEffect to set show with setShow(items.length > 0);. Would it be simpler to ...

Extracting data from website's table using JavaScript and opening the link in href

My goal is to extract the details page for each link found on this particular page. The link provides access to all the information required: PAGE However, I'm interested in extracting details from pages that have links like this: href="javascr ...

Importing an array into DynamoDB using a JSON string with boto3

When it comes to uploading a JSON file to an AWS DynamoDB table in Python, I have been using a script that I found on this particular page. However, I am facing a challenge in understanding whether Python can be instructed to split a single string from the ...

Jackson will not convert null values using a personalized Serializer

One issue I encountered was with a custom bean serializer in Jackson that resulted in null properties being excluded from the output JSON. To reproduce the problem, consider the following code snippet: // Code example goes here Upon running the above cod ...

Using jQuery to combine the values of text inputs and checkboxes into a single array or string

I need to combine three different types of items into a single comma-separated string or array, which I plan to use later in a URL. Is there a way to merge these three types of data together into one string or array? An existing POST string User input f ...

Tips for filling jstree with information in Grails

I am currently facing difficulties in populating a jstree within a Grails gsp. Here is what I have attempted so far (rewritten for clarity): <script> $("#treeView").jsTree(); </script> <div id="treeView"> <g:each in="${atomMa ...

Tips for modifying environment variables for development and production stages

I am looking to deploy a React app along with a Node server on Heroku. It seems that using create-react-app should allow me to determine if I'm in development or production by using process.env.NODE_ENV. However, I always seem to get "development" ev ...

Click event not functioning correctly in Internet Explorer

When using jQuery, I have the following code: <script type="text/javascript"> $(document).ready(function(){ $('body').on('click', '.add-photo',function() { $("#images").append($('<input/>').attr(&apo ...

What is the jQuery syntax for targeting a specific element within an object?

Is there a way to access a sub element from $(this)? For instance, how can I specifically select a span element inside the this object? ...

Using TypeScript's type casting functionality, you can easily map an enum list from C#

This is a C# enum list class that I have created: namespace MyProject.MyName { public enum MyNameList { [Description("NameOne")] NameOne, [Description("NameTwo")] NameTwo, [Description("NameThree")] NameThree ...

Assign Monday as the selected day of the week in the MUI Datepicker 6

I am currently using version 6 of the material ui Datepicker and I am trying to configure it so that the week starts on Monday. import React from "react"; import { DatePicker as DatePickerDestop } from "@mui/x-date-pickers/DatePicker"; ...