1

I am converting complex object using JSON stringify.

I want this kind of output so I can bind it easily with my model.

DateRequired: "2019-02-02"
DeliveryDestination: "test"
ProjectCode: "002P"
RequestItems: {InventoryItemsId: "2", Brand: "NIKE", Types: "Casual", Specification: "Mentality", ItemName: "Wild"},
{InventoryItemsId: "3", Brand: "PUMA", Types: "Running", Specification: "Energy", ItemName: "Wild"}

But instead I am getting this one.

DateRequired: "2019-02-02"
DeliveryDestination: "test"
ProjectCode: "002P"
RequestItems: Array(2)
0: {InventoryItemsId: "2", Brand: "NIKE", Types: "Casual", Specification: "Mentality", ItemName: "Wild", …}
1: {InventoryItemsId: "3", Brand: "PUMA", Types: "Running", Specification: "Energy", ItemName: "Wild", …}
length: 2
__proto__: Array(0)
__proto__: Object

This is the code that post the data:

var items = postAllItems(); //this is an array
                var materialRequest = {
                    'DateRequired': $('#txtDateRequired').val(),
                    'ProjectCode': $('#txtProjectCode').val(),
                    'DeliveryDestination': $('#txtDeliveryDestination').val(),
                    'RequestItems': items
            };

 postMaterialRequest(materialRequest);

function postMaterialRequest(materials) {
            $.ajax({
                contentType: 'application/json',
                type: 'POST',
                url: '/api/PostMaterial',
                data: JSON.stringify(materials),
                success: function (data) {
                    console.log("Info Save " + data);                   
                },
                failure: function (response) {
                    console.log('Failed to save.');
                }
            });
        }

This is what I am getting from Web API

enter image description here

j1rjacob
  • 411
  • 11
  • 27
  • The second output is what you get when you *don't* use `JSON.stringify`: it is typically what you get in console-format. – trincot Mar 01 '19 at 23:43
  • Or use ‘JSON.stringify(object,null,2)’ for a prettyfied variant – Geert-Jan Mar 01 '19 at 23:54
  • @Geert-Jan i tried but no luck – j1rjacob Mar 02 '19 at 07:00
  • thanks for the info @trincot I updated my question to make it clearer. – j1rjacob Mar 02 '19 at 09:29
  • This looks like your question is really about something else: you cannot expect to display the result of an asynchronous result synchronously. See [this Q&A](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). For the rest, the question does not make clear what `Count` is, what `_items` is, what `pimx.DTOs.RequestItemDto[0]` is (circling it in the screenshot does not really help more), and how they relate to your question. – trincot Mar 02 '19 at 09:41
  • thanks for the insight is just i don't know much about this asynchronous, can you give me links/answer so can understand it. yeah i think i am mixing asynchronous with synchronous. sorry for the image it gives wrong idea about the question. @trincot – j1rjacob Mar 02 '19 at 09:57
  • The referenced Q&A has all the info. Check it out. – trincot Mar 02 '19 at 10:02

2 Answers2

1

It is the right kind of output - it's just the console's way of showing an object. Using StackOverflow's console, or using JSON.stringify, shows the output you want:

var myObj = {
  DateRequired: "2019-02-02",
  DeliveryDestination: "test",
  ProjectCode: "002P",
  RequestItems: [{
      InventoryItemsId: "2",
      Brand: "NIKE",
      Types: "Casual",
      Specification: "Mentality",
      ItemName: "Wild"
    },
    {
      InventoryItemsId: "3",
      Brand: "PUMA",
      Types: "Running",
      Specification: "Energy",
      ItemName: "Wild"
    }
  ]
};

console.log(myObj);
console.log(JSON.stringify(myObj));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • when i try to put it manually it works ex. RequestItems: {InventoryItemsId: "2", Brand: "NIKE", Types: "Casual", Specification: "Mentality", ItemName: "Wild"}, {InventoryItemsId: "3", Brand: "PUMA", Types: "Running", Specification: "Energy", ItemName: "Wild"} – j1rjacob Mar 02 '19 at 07:01
0

I resolve my problem by using the code below, my problem is all about not mixing synchronous with asynchronous function. In which the ajax post finish first. I used setTimeout to delay ajax post. Thanks to @trincot link.

function createObject() {
            var mr = { DateRequired: $('#txtDateRequired').val(), ProjectCode: $('#txtProjectCode').val(), DeliveryDestination: $('#txtDeliveryDestination').val(), RequestItems: [] };
            for (var i = 0; i < insMaterials.length; i++) {
                var mtr = insMaterials[i];
                alert(mtr);
                var RequestItems = {
                    'InventoryItemsId': mtr.InventoryItemsId,
                    'Brand': mtr.Brand,
                    'ItemName': mtr.ItemName,
                    'Quantity': mtr.qty,
                    'RefNo': 3,
                    'Comment': mtr.remarks,
                    'Specification': mtr.specification,
                    'Types': mtr.types,
                    'Unit': mtr.qty
                };
                mr.RequestItems.push(RequestItems);
            }
            return JSON.stringify(mr);
        }


function postMaterialRequest() {
            $.ajax({
                contentType: 'application/json',
                async: false,
                type: 'POST',
                url: '/api/PostMaterial',
                data: (createObject()),
                success: function (data) {
                    console.log("Info Save " + data);
                    toastr.success('Request was submitted successfully!');
                    del();
                },
                failure: function (response) {
                    console.log('Failed to save.');
                    toastr.error('Failed to save.');
                }
            });
        }


postAllItems();
setTimeout(postMaterialRequest, 3000);
j1rjacob
  • 411
  • 11
  • 27