在javascript中,测试属性是否深深嵌套在对象图中?(In javascript, test for property deeply nested in object graph?)

我从CouchDB数据库中获得了一组完全不同的复杂JSON对象。 每个包含很多级别的嵌套属性 - 例如,

tps_report.personnel_info.productivity.units_sold = 8  

我想通过这些对象进行迭代并对它们进行处理:例如,

// writes units sold from each TPS report:
for (i in tpsReports) {
  if (tpsReports[i].personnel_info.productivity.units_sold < 10) {
    fireEmployee();
  }
}

问题是许多TPS报告没有设置所有这些属性。 因此,如果我尝试这样做,那么在第一次循环获取到没有“personnel_info”属性的报告时,会出现错误,从而尝试查找“undefined”的“productivity”属性。 我宁愿发生的是条件只是跳过它并继续。

我看到了两种方式,这两种方式对我来说都显得很丑陋

  1. 分别使用嵌套条件测试每个属性
  2. 将行放在try / catch块中以捕获错误并忽略它

我更喜欢的是PHP的isset()函数,它不会抛出错误,无论提供什么内容 - 它只会告诉你你正在寻找的特定变量是否存在。 所以,就像

// writes units sold from each TPS report:
for (i in tpsReports) {
  if (isset(tpsReports[i].personnel_info.productivity.units_sold)){
    if (tpsReports[i].personnel_info.productivity.units_sold < 10) {
      fireEmployee();
    }
  }
}

有什么想法吗?


I've got a collection of disparate, complex JSON objects from a CouchDB database. Each contains many levels of nested properties--for example,

tps_report.personnel_info.productivity.units_sold = 8  

I want to iterate through these objects and do stuff with them: for instance,

// writes units sold from each TPS report:
for (i in tpsReports) {
  if (tpsReports[i].personnel_info.productivity.units_sold < 10) {
    fireEmployee();
  }
}

The problem is that many TPS reports don't have all these properties set. So if I try this, I'll get an error the first time the loop gets to a report without the "personnel_info" property and thus tries to find the "productivity" property of "undefined." What I'd rather happen is that the conditional just skips it and continues.

I see two ways around this, both of which seem ugly to me

  1. test for each property separately with nested conditionals
  2. enclose the line in a try/catch block to catch the error and ignore it

What I'd prefer would be something like PHP's isset() function, which won't throw an error regardless of what you feed it--it'll just tell you whether the particular variable you're looking for exists or not. So, like

// writes units sold from each TPS report:
for (i in tpsReports) {
  if (isset(tpsReports[i].personnel_info.productivity.units_sold)){
    if (tpsReports[i].personnel_info.productivity.units_sold < 10) {
      fireEmployee();
    }
  }
}

Any thoughts?


原文:https://stackoverflow.com/questions/4343028
2023-09-07 11:09

满意答案

尝试使用当前年份的'c' ,如:

$('#dobDate').datepicker({yearRange : '1920:c',changeYear: true});

也使用changeYear: true

工作演示Fiddle.net


Try using 'c' for the current year like:

$('#dobDate').datepicker({yearRange : '1920:c',changeYear: true});

use also the changeYear: true

working demo Fiddle.net

相关问答

更多

jQuery datepicker年显示(jQuery datepicker years shown)

如果您往下看演示页面,您将看到一个“限制日期戳”部分。 使用下拉列表来指定“ Year dropdown shows last 20 years ”演示,并点击查看源: $("#restricting").datepicker({ yearRange: "-20:+0", // this is the option you're looking for showOn: "both", buttonImage: "templates/images/calendar.gif...

jQuery UI:Datepicker设置年份范围下拉到100年(jQuery UI: Datepicker set year range dropdown to 100 years)

您可以使用此选项在每个文档中设置年份范围http://api.jqueryui.com/datepicker/#option-yearRange yearRange: '1950:2013', // specifying a hard coded year range 或这样 yearRange: "-100:+0", // last hundred years 从文档 默认值:“c-10:c + 10” 相对于当前选定年份(“c-nn:c + nn”),绝对(“nnnn: nnnn“)或这些...

如何将Bootstrap Datepicker日期视图限制为Year(How to limit Bootstrap Datepicker date view to just Year)

试试这个解决方案 $('.datepicker').datepicker({ autoclose: true, format: " yyyy", viewMode: "years", minViewMode: "years", startDate: '2014', endDate: new Date(), }); 见JsFiddle 。 我希望它适合你,谢谢。 Try this solution : $('.datepicker').datepi...

Datepicker - 仅限年份?(Datepicker - year only?)

Silverlight for Windows Phone Toolkit中的DatePicker控件没有这种直接自定义! 您必须更改选择器控件及其使用的完整页面; 你可以在这里查看有关DatePicker定制的一些信息,虽然它很稀疏...... The DatePicker control in the Silverlight for Windows Phone Toolkit doesn't have that kind of direct customization! You'll have...

展示未来的一年(Display year in the future)

试试这个,这会产生一个从2016年到今年的年份列表 WITH CTE_TEST AS( SELECT 2016 AS NYEAR UNION ALL SELECT NYEAR+1 FROM CTE_TEST WHERE NYEAR+1 <= YEAR(GETDATE()) ) SELECT * FROM CTE_TEST Try this, this will generate a list of Year from 2016 to current ...

如何在datepicker下拉列表中显示从1920年到当年的正确年份(How to display correct years from 1920 to current year in datepicker drop down for year)

尝试使用当前年份的'c' ,如: $('#dobDate').datepicker({yearRange : '1920:c',changeYear: true}); 也使用changeYear: true 工作演示Fiddle.net Try using 'c' for the current year like: $('#dobDate').datepicker({yearRange : '1920:c',changeYear: true}); use also the changeYea...

jQuery DatePicker:如何将year数组传递给yearRange下拉列表(jQuery DatePicker: How to pass array of years to the yearRange drop down)

根据https://api.jqueryui.com/datepicker/#option-yearRange - 根据文档,这是不可能的。 您只能设置一个连续的范围。 但是,这个问题真的让我们直接回到了前面问题中讨论的XY问题 - 基本上,如果您的结束日期为空而不是使用假装日期,那么您首先不会遇到这个问题。 而且你的应用程序的数据质量会更好。 我已经知道你不想听到这些,但这是问题的根源。 如果您无法更改数据库中的内容,那么至少在UI层中删除这些日期 As per https://api.jque...

jQueryUI DatePicker自定义年份(jQueryUI DatePicker Customizing the Year)

点击这里观看演示。 当您发现自己超出范围时,jQuery UI源很容易修改。 您只需要更改_generateMonthYearHeader的函数定义: // StackOverflow question: Add option for N/A html += '<option value="1900">N/A</option>'; 并将此更改改为_selectDay以省略选择N / A的年份。 // StackOverflow question: format the date if (inst...

JQuery Datepicker - 添加年份(JQuery Datepicker - Add Years)

尝试使用Date的setFullYear和getFullYear : $("#equipment_purchaseDate").datepicker({ dateFormat: 'dd/mm/yy', onSelect: function(dateStr) { var d = $.datepicker.parseDate('dd/mm/yy', dateStr); var years = parseInt($("#equipment_warranty...

jQuery Datepicker将默认日期设置为“当前月份,当前日期,(当前年份-18)”(jQuery Datepicker Set Default Date to “current month, current day, (current year-18)”)

尝试 var d = new Date(); var year = d.getFullYear() - 18; d.setFullYear(year); $('#BirthDate').datepicker({ changeYear: true, changeMonth: true, yearRange: '1920:' + year + '', defaultDate: d}); 演示: 小提琴 Try var d = new Date(); var year = d.getFullYear(...

相关文章

更多

javascript 问题

&lt;s:iterator value=&quot;list_latest_course&quot; ...

Object Oriented Programming

Some might also contend that inheritance should be ...

请教javascript问题

&lt;script type=“javascript”&gt; function test(){ ...

could not find system property or JNDI

Thanks everyone!! Finally got a solution for this p ...

Guava学习笔记:复写的Object常用方法

  在Java中Object类是所有类的父类,其中有几个需要override的方法比如equals,h ...

javascript快速入门

本节内容包括:js使用,变量简介,变量的作用域,变量的类型

Cannot expose request attribute 'website' because of an existing model object of the same name 的解决方案

在使用springmvc+freemarker,有可能你会遇到以下异常(如:资源找不到重定向到404的 ...

Hadoop 0.21如何运行单个test case

研究 Hadoop 0.21代码时,很多情况下需要运行单个test case,如果新增了功能要测试 ...

从 prototype.js 深入学习 javascript 的面向对象特性

从 prototype.js 深入学习 javascript 的面向对象特性,js是一门很强大的语言, ...

JavaScript实现长按功能问题

JScript code var dt2; var st; function test() { ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本