0

I have a file that gets a json response like this:

{
   total": 86,
   "data": [
    {
        "Id": 2,
        "Name": "User One",
        "Shipping": 1,
        "Created": "25 March 2017"
    },
    {
        "Id": 3,
        "Name": "User Two",
        "Shipping": 2,
        "Created": "25 March 2017"
    },
    {
        "Id": 4,
        "Name": "User Three",
        "Shipping": 3,
        "Created": "26 March 2017"
    }
  ]
}

I want to run through this result and change all the Shipping values to:

1 Post Office

2 PostNet

3 Courier

In my code I do:

$.each(data.data, function () {
      $.each(this, function (key, value) {
         if(key == 'Shipping') {
             switch(value) {
               case 2:
                   ? = 'PostNet';
                   break;
               case 2:
                   ? = 'Courier';
                   break;
               default:
                   ? = 'Post Office';
                   break;
               }

         }
      });
});

I don't know how to get the right array key so I can change it, that's where I put the ?.

Can anyone please help?

2 Answers 2

1

You're close.

Loop through the JSON object. When key matches string, then make the switch. Once you match one of the values, change the parent loop value into the desired value.

Change your JS into this:

$.each(data.data, function (key, value) {    
    $.each(this, function(k, v) {
        if(k == 'Shipping') {
             switch(v) {
                    case 1:
                   value.Shipping = 'PostNet';
                   break;
                case 2:
                   value.Shipping = 'Courier';
                   break;
                default:
                   value.Shipping = 'Post Office';
                   break;
             }
        }
    });
});

https://jsfiddle.net/zeopL56n/2/ (See console log)

Sign up to request clarification or add additional context in comments.

1 Comment

God bless your soul... :) Thank you
0

You have to do it this way:

$.each(data.data, function () {
    switch(this.Shipping) {
    case 1: 
        this.Shipping='PostNet';
        break;
    case 2: 
        this.Shipping='Courier';
        break;
    default: 
        this.Shipping='Post Office';
    }
});

Look at the console to see the updated object.

Here is a fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.