Kusch Kusch - 1 year ago 167
Javascript Question

JS: How to check if the JSON contains a specific value


Im working with an array containing multiple events (names & dates) for each event i have to create a point in a SVG.

For each new Date X = X + 5.
For each event on the same date Y = Y + 5.


event 1: date = 1970 X = 10 & Y = 10

event 2: date = 1970 X = 10 & Y = 15

If a point has been drawn i save the position in an JSON. How can i now validate if the position exists in the JSON?

What i tried

var var events = [{TITLE:"event 1", DATE:"1970"},
{TITLE:"event 2", DATE:"1970"},
{TITLE:"event 3", DATE:"1970"}];
var pos_reserved = [];
var X = 10;
var Y = 10;
if (pos_reserved.X != X && pos_reserved.Y != Y){
Y = 30;
else if (pos_reserved.X == X && pos_reserved.Y == Y)
Y = 10;
elseĀ {}
pos_reserved.push({"X": X,"Y": Y});
create_point(X, Y);

Answer Source

I'm not sure I understand your problem fully but I'm gonna try to help you anyway...

In my opinion, one possibility would be to save the data in an object pos_reserved and do something like that

var pos_reserved = {};

// returns if a position is already reserved or not
function isReserved(x, y){
  if (!pos_reserved[x])
    return false;
  if (!pos_reserved[x][y])
    return false;
  return true;

// reserve a position
function reservePosition(x, y, someInfo){
  // only reserve position if it's not already reserved
  if (!isReserved(x, y)){
    // check if you already have points with this x
    if (!pos_reserved[x]){
      // create one if needed
      pos_reserved[x] = {};
    // save the point
    pos_reserved[x][y] = someInfo;
    // dosomething...

That's it... i think it's the best solution because your JSON object acts like a matrix... So you can easily access every points you saved earlier...

I added 'someValue' to show you that you can save information about this point. You can give a name or whatever you want... It's up to you, but you don't have to use it as weel ;)

Let me know if you have questions ;)


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download