Sigal Zahavi
Sigal Zahavi

Reputation: 1073

How to change values in JSON array

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?

Upvotes: 0

Views: 587

Answers (2)

lhavCoder
lhavCoder

Reputation: 961

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

Upvotes: 0

Red
Red

Reputation: 7324

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)

Upvotes: 1

Related Questions