[英]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. 我正在使用包含每个事件的多个事件(名称和日期)的数组,我必须在SVG中创建一个点。
For each new Date X = X + 5. For each event on the same date Y = Y + 5. 对于每个新日期X = X +5。对于同一日期的每个事件,Y = Y + 5。
ex: 例如:
event 1: date = 1970 X = 10 & Y = 10 事件1:日期= 1970 X = 10&Y = 10
event 2: date = 1970 X = 10 & Y = 15 事件2:日期= 1970 X = 10&Y = 15
If a point has been drawn i save the position in an JSON. 如果已绘制点,则将位置保存为JSON。 How can i now validate if the position exists in the JSON?
现在如何验证JSON中是否存在该位置?
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);
I am not sure I understand the exact question, but I'll answer to the title. 我不确定我是否理解确切的问题,但我会回答标题。
UnderscoreJS is your best friend! UnderscoreJS是您最好的朋友!
_.find(events, {DATE: "1970"})
//returns 1st object that matches the year: Object {TITLE: "event 1", DATE: "1970"}
_.filter(events, {DATE: "1970"}).length
//returns the number of objects with that year: 3
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 我认为,一种可能性是将数据保存在pos_reserved对象中,然后执行类似的操作
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; } else{ // 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... 就这样...我认为这是最好的解决方案,因为您的JSON对象的行为就像一个矩阵...因此您可以轻松访问之前保存的每个点...
I added 'someValue' to show you that you can save information about this point. 我添加了“ someValue”以向您显示可以保存有关这一点的信息。 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 ;) 让我知道你是否有问题;)
Romain 罗曼
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.