Getting values from jQuery object array based on key not array number

48 Views Asked by At

I need to get values from an object returned via $.post but the order of the 2 arrays can change, so I need to get them based on the key. The problem is that the key is returned inside the array. Example below.

{
Id: "AETVXXXXXXXX", HasError: false, Error: null, FinanceQuotations: Array(2)}
    Error: null
    FinanceQuotations: Array(2)
        0:
            Blocks: [{…}]
            Error: null
            Finance: {Key: "HP", Notifications: Array(0), Quote: {…}, Product: {…}, Retailer: {…}}
            HasError: false
            __proto__: Object
        1:
            Blocks: [{…}]
            Error: null
            Finance: {Key: "PCP", Notifications: Array(0), Quote: {…}, Product: {…}, Retailer: {…}}
            HasError: false
            __proto__: Object
            length: 2
            __proto__: Array(0)
        HasError: false
        Id: "AETVXXXXXXXX"
        __proto__: Object
}

I would normally drill down into the array and assign the value to the var using something like the below:

var durationValue = (value.FinanceQuotations[1].Blocks[0].Details[0].DisplayValue);

But because the array order is now liable to change, it won't always return the same product first in the array return the wrong values.

How can I loop over the arrays and get the values for the key? The two keys, in this case, are "HP" and "PCP"...

Can anyone help me with this?

Thanks in advance.

1

There are 1 best solutions below

2
NoSkill On

The only way is creating "associative array"-object like this:

var a = {
  "HP": ...
  "PCP": ...
  "OTHER_KEY": ...
}

and then iterate items using "for-in"-cycles:

for (key in a) {
   alert(key);
   alert(a[key]);
}