0
How do I display values with the same index number
var myobj = { "date": ["somedata1","somedata2","somedata3"], "event": ["somedata1","somedata2","somedata3"], "venue": ["somedata1","somedata2","somedata3"] } My intention is that the user enters the date and gets the event and venue with the same index as output.
10 Respuestas
+ 7
Aleksandar Stevanovic
He would need to loop every object to find the right date.
for(var a = 0; a < myobj.length; a++) {
if(myobj[a]["date"] == input) {
var event = myobj[a]["event"];
var venue = myobj[a]["venue "];
//do something
return;
}
}
+ 5
Something like this?
var input = prompt("date:");
var dateIndex = myobj["date"].indexOf(input);
var event = myobj["event"][dateIndex];
var venue = myobj["venue"][dateIndex];
+ 4
for ... myobj.date.length
If you use 'today', you'll get three alerts because you don't break once found.
+ 2
I regularly use:
for(var i in myobj.date) { ... }
which is easier to visually parse in my opinion; it behaves similarly here, setting i to the index.
+ 1
Toni is right, if you have a LOT of data keep in mind that a loop will take its time, in lodash you can simplify it like _.find(myobj, blah blah ) but again it will have a loop within lodash... Anyway good luck
+ 1
finally solved. only one error in Toni's code. it is myobj.date.length. Final code looks like this
var myobj = {
"date": ["today","morro","yday"],
"event": ["dance","sing","run"],
"venue": ["here","there","somewhere"]
}
input = prompt ("enter date");
for(var a = 0; a < myobj.date.length; a++) {
if(myobj.date[a] ==input) {
var event = myobj.event[a];
var venue = myobj.venue[a];
alert (event +" " +venue );}
}
0
thanks for the response. i wish it is this simple.
I am prompting user to input date
I want to be able to get the index of the date entered
then display myobj[event][i] and myobj [venue][i], where i is the index of the date.
0
Why don't you make it like array of objects? Like myobj = [{date: 'somedata1' , event: 'somedata1', venue: 'somedata1}, {date:' somedata2', etc etc]
Your data will be in one object...
Also you can try lodash... It will be easier to manipulate data
0
I do appreciate the assistance. I will try to rearrange the data even though it will be very difficult. I have a very large data to work with.
0
I tried this but got no response. not sure what the error is
var myobj = {
"date": ["today","morro","yday"],
"event": ["dance","sing","run"],
"venue": ["here","there","somewhere"]
}
input = prompt ("enter date");
for(var a = 0; a < myobj.length; a++) {
if(myobj.date[a] ==input) {
var event = myobj.event[a];
var venue = myobj.venue[a];
alert (event, venue);}
else {alert ("try again");}
}