Reputation: 355
I have a JSON output below :
[
{
positionCode: "POS1",
positionName: "POSITION 1",
positionDescription: "",
parentPosition: "POS2",
},
{
positionCode: "POS2",
positionName: "POSITION 2",
positionDescription: "",
parentPosition: "POS3",
}
]
This JSON result is from my Web API that looks like this :
return new JsonResult(query.Select(x =>
new { x.PositionCode, x.PositionName , x.PositionDescription , x.ParentPosition }).ToList());
However, my desired output is like this :
What things should be done to achieve my desired result? In my javascript code or in my C# Web API? Thank you!
Upvotes: 2
Views: 1241
Reputation: 12274
You are selecting an anonymous object with string properties when you want an array of the string values.
return new JsonResult(query.Select(x =>
new string[] {
x.PositionCode,
x.PositionName,
x.PositionDescription,
x.ParentPosition
}).ToList()
);
Upvotes: 1
Reputation: 12900
Assuming you have a similar setup to this:
var data = 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 options:
Handle it in your C# code
Looks like you already have linq
, so just turn your List<T>
into an array or strings:
data.Select(d => new[] {d.ParentPosition, d.PositionCode, d.PositionDescription, d.PositionName}).ToArray()
Handle it in 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(r => Object.values(r))
console.log(reformatted);
Upvotes: 2
Reputation: 6643
JavaScript's Object.values() can be used to do that.
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);
Upvotes: 2