웃웃웃웃웃
웃웃웃웃웃

Reputation: 362

get a month from the json objec using amount

I have one variable which is store diff. amount like 147421
and i want to find with this amount want to display there month from JSON

My JSON Object looks like this:

var array = [
    {
        amount: 12185,
        month: "JANUARY",
        year: "2010"
    },
    {
        amount: 147421,
        month: "MAY",
        year: "2010"
    },
    {
        amount: 2347,
        month: "AUGUST",
        year: "2010"
    }
];

How can I do this?.
Select month where amount == 12185

Upvotes: 0

Views: 92

Answers (5)

A.T.
A.T.

Reputation: 26312

try using filter

function getMonth(a)
{
    var j = array.filter(function(i)
            {
               if(i.amount === a)
               {
                  return i.month;
               }
            });

    return j[0].month; // here we get first matched result
}

var res = getMonth(12185);

res will contain JANUARY here.

Upvotes: 0

JEYASHRI R
JEYASHRI R

Reputation: 452

Try this, Dynamic code

 <div><input type="button" value="12185" class="className"/>
 <input type="button" value="147421"  class="className"/>
 </div>

for (var i in my_object) {
    var cur = my_object[i];
    $('input[value=' + cur.amount + ']').each(function() {
        var msg = 'Sales Month: ' + cur.month + ' Number: ' + cur.year;

        $(this).parent('div').append('<div>' + msg + '</div>');
    });
}

Fiddle: http://jsfiddle.net/jeyashri/HdgmN/3/

Upvotes: 0

Surya Narayan
Surya Narayan

Reputation: 558

You can filter data using .filter

var result = array.filter(function(item) {
    return item.amount == 12185;
});

DEMO

Upvotes: 6

Linga
Linga

Reputation: 10553

Here is the working Fiddle

var result;
var your_value=12185;
for(var i=0;i<array.length;i++)
{
    if (your_value == array[i].amount)
    {
        result=array[i].month;
        break;
    }
}
alert(result);

Upvotes: 0

W.K.S
W.K.S

Reputation: 10095

You could use a function like this; though the array would have to be global. Here's a JSFiddle.

function getMonth(amount){

    month = "";

    for(i = 0;i<array.length.i++){
        if(array[i].amount === amount){
            month = array[i].month;
            break;
        }
    }

    return month;
}

Upvotes: 1

Related Questions