Kamnibula
Kamnibula

Reputation: 88

Javascript to get last value of json object

I need the last element from the json object like that:

{
  "results": {
    "collection1": [
      {
        "price": [
          "95",
          "80"
        ],
      },
      {
        "price": "68"
      },

.....

This is my function:

function transform(data) {
  for (var i = 0; i < data.results.collection1.length; i++){
    var price = data.results.collection1[i].price;
    data.results.collection1[i].price = price[price.length-1];
  }

  return data;
}

I need to get last value of price. In first one it will be 80 in second 68. When I use

price_last = data.collection.price[data.collection.price.length-1];

it gives me 80 for first price element and 8 in second.. But I need 68.

Upvotes: 1

Views: 1764

Answers (4)

devconcept
devconcept

Reputation: 3685

Change your function to this

function transform(data) {
        for (var i = 0; i < data.results.collection1.length; i++) {
            var price = data.results.collection1[i].price;
            if (Object.prototype.toString.call(price) === '[object Array]'){
                data.results.collection1[i].price = price[price.length - 1];
            } else {
                data.results.collection1[i].price = price;
            }
        }

        return data;
    }

Note: Array.isArray is an Ecmascript 5 function and might not be defined in all enviroments.

Upvotes: 0

Leosvel
Leosvel

Reputation: 81

try this:

if (Array.isArray(data.collection.price)) {
    price_last = data.collection.price[price.length-1];
} else {
    price_last = data.collection.price;
}

Upvotes: 3

Ben Jaspers
Ben Jaspers

Reputation: 1546

The issue is that the first price property is an array and the second is a string. Ideally, you would make price an array even if you only have one price.

Failing that, you have to check if the price property is an array or not:

data.collection.price instanceof Array ? 
    data.collection.price[data.collection.price.length - 1] : 
    data.collection.price;

This statement will take the last element if it's an array or just return the price property if it's not.

Upvotes: 0

M&#225;rcio Gonzalez
M&#225;rcio Gonzalez

Reputation: 1040

Try data.collection1[data.collection1.length - 1].price;

Upvotes: -1

Related Questions