Using Javascript I want to have a JSON or array that will store id & ip data pairs, such that if I want the ip of a particular id=123, I can easily get it, ie by using data[123] or data['123']['ip'].
I tried this but cant seem to select the ip based on id:
var connected_clients = {
"clients": [{id: "12345", ip: "123.123.123.123"}]
};
Also tried using this below, but I cant seem to add new id/ip pairs to it…
var connected_clients = {
"12345": {
id: "12345",
ip: "123.123.123.123"
}
};
How should it be done?
(First up, you don’t have “a JSON”, you have an object. JSON is a string representation of data – or you could think of it as an object serialised to string form. Anyway…)
If you want to be able to look up the details for a known id, your second structure will work fine.
With more clients it would look like this:
And you’d get the ip of client “12346” like this:
If you want to add a client:
If you want to check if a particular id already exists:
To iterate through all the clients:
Further reading: