Reputation: 868
I have a Javascript object with the following format assigned to a javascript variable:
var events =
[
{
"Id":20,
"CustomerId":9,
"CustomerName":"Mark Wikkins",
"Code":"CT6789",
"CustomerDate":"\/Date(1466679600000)\/",
"Levels":[
{
"Id":92,
"Nivel":0,
"Code1":"Sales",
"Code2":null,
"Description":"Customer",
},
{
"Id":94,
"Nivel":0,
"Code1":"Sales",
"Code2":null,
"Description":"Customer",
}
]
},
{
"Id":21,
"CustomerId":14,
"CustomerName":"John Stweart",
"Code":"CT70000",
"CustomerDate":"\/Date(146667970000)\/",
"Levels":[
{
"Id":102,
"Nivel":0,
"Code1":"Jobs",
"Code2":null,
"Description":"Customer",
},
{
"Id":106,
"Nivel":"0",
"Code1":"Commissions",
"Code2":null,
"Description":"Customer",
},
{
"Id":113,
"Nivel":0,
"Code1":"Organizations",
"Code2":null,
"Description":"Customer",
}
]
}
];
And I have a drop down with the following Text and Values
<select name="customers_select" id="customers_select">
<option value="92">Sales</option>
<option value="106">Commisions</option>
<option value="113">Organizations</option>
</select>
If I wanted to get the CustomerDate
upon selecting from the drop down, what would be the best way to do it?
As you can see the values of the select (dropdown) map to a Level Id, but the level is a property of the parent object in the Javascript Object
.
So if I select "Commisions"
from the drop down, i need to evaluate my variable events and obtain the CustomerDate for the second object.
Is there something like I could get the CustomerDate by passing the value of the select from the events Javascript Object
array?.
Upvotes: 1
Views: 104
Reputation: 6309
Two ways you can do this.
Loop through your JavaScript object and map Level_ids to CustomerDates like this:
var hash = {};
hash["level-102"] = "\/Date(146667970000)\/";
hash["level-106"] = "\/Date(146667970000)\/";
hash["level-113"] = "\/Date(146667970000)\/";
... and so on
You can do that by looping through your object with jQuery's .each()
function (and you'll need another one inside that to traverse the Level object).
In the JavaScript select event, you can take the id and make a string "level-" + id
and look up in your hash table: var customerDate = hash["level-" + id];
Keep your JavaScript object as-is, and when the user selects from the drop-down, it fires an event handler that traverses through your complex object looking for the level_id. While doing this it is remembering the current "CustomerDate" so when it is found, you break out of the search loop.
Upvotes: 2