如何测试Javascript数组中是否存在对象?(How do I test if an object exists in a Javascript array?)

我已经看到了其他问题,我已经尝试了过滤功能,但我不确定我是否正确使用它。

基本上我有一个对象数组,如下所示:

[{"hour":"6 am", "date":"2012-12-01"},{"hour":"7 am", "date":"2012-12-01"}]

我循环了一段时间,每天我都会在早上6点到晚上9点之间循环。 如果上述数组中存在小时(如该特定日期的小时)。 我想将它标记为可用于新对象,然后传递给新数组。 以下是我目前使用的代码。

for(var i = 0; i < dayCount; i++){//Loop through the days that exist in the schedule
    day = new Object();
    day.date = Date.parse(startDate).add(i).days();
    day.dayName = weekday[day.date.getDay()]
    day.hours = new Array();
    for(var j = 6; j < 22; j++){ //Loop through hours of the day seeing if they're available/scheduled, etc.
        if(j<=12){
            thisHour = j +' am';
        } else{
            thisHour = j-12 + ' pm';        
        }
        var thisIsAvailable = $(assignedHours).filter(function(){
                return assignedHours.hour == thisHour && assignedHours.date == day.date.toString("yyyy-MM-dd");
            });
        var thisIsScheduled = 0;
        day.hours.push({hour: thisHour,available: thisIsAvailable, scheduled: thisIsScheduled});
    }
daysInSchedule.push(day);
}   

几个笔记。 我在day.date属性上使用.toString(),因为它是以JS Date格式格式化的,我正在比较它的值是MYSQL Date格式。 我已经提醒(谈论旧学校调试)thisIsAvailable.length,我每次都得到0。 任何想法都表示赞赏。 谢谢!

编辑:刚刚意识到我忘了告诉你一切非常重要的事情。 我给你的数组包含在变量Named assignedHours中。 很抱歉离开了。

编辑2:为了澄清,我的问题是在两个代码摘录之间的位置。 我试图看看给定数组中的一个对象是否匹配循环中的日期和小时,以及我正在运行的嵌套循环。 如果确实如此,我想将其传递给一个新对象,然后我将其推入当天的小时数组中。 如果没有,那么我仍然传递对象但是为0可用。


I've seen other questions, and I've tried the filter function, but I'm not sure if I'm using it correctly.

Essentially I have an array of objects that looks like this:

[{"hour":"6 am", "date":"2012-12-01"},{"hour":"7 am", "date":"2012-12-01"}]

I'm looping through a set period of days, and on each day I'm looping through the hours between 6am and 9pm. If the hour(as in the hour on that specific date) exists in the above array. I want to mark it as available in a new object that I then pass to a new array. Below is the code I'm currently using.

for(var i = 0; i < dayCount; i++){//Loop through the days that exist in the schedule
    day = new Object();
    day.date = Date.parse(startDate).add(i).days();
    day.dayName = weekday[day.date.getDay()]
    day.hours = new Array();
    for(var j = 6; j < 22; j++){ //Loop through hours of the day seeing if they're available/scheduled, etc.
        if(j<=12){
            thisHour = j +' am';
        } else{
            thisHour = j-12 + ' pm';        
        }
        var thisIsAvailable = $(assignedHours).filter(function(){
                return assignedHours.hour == thisHour && assignedHours.date == day.date.toString("yyyy-MM-dd");
            });
        var thisIsScheduled = 0;
        day.hours.push({hour: thisHour,available: thisIsAvailable, scheduled: thisIsScheduled});
    }
daysInSchedule.push(day);
}   

A couple notes. I use .toString() on the day.date property because it is formatted in JS Date format and the value I'm comparing it against is in the MYSQL Date format. I've alerted (talk about old school debugging) thisIsAvailable.length, and I get 0 everytime. Any ideas are appreciated. Thanks!

EDIT: Just realized I forgot to tell you all something very important. The array I give you is contained in the variable Named assignedHours. Sorry about leaving that out.

EDIT 2: To clarify, my question is in the bit between the two code excerpts. I'm trying to see if one of the objects in the given array matches the day and hour in the loop, and nested loop I'm running through. If it does I want to pass that on to a new object which I then push into the hours array of the day. If not then I still pass the object but with a 0 value for it being available.


原文:https://stackoverflow.com/questions/13179038
2022-02-18 14:02

满意答案

更改

public ResponseEntity<User> handleFileUpload(@RequestParam("user") User user, @RequestPart("file") MultipartFile file)

public ResponseEntity<User> handleFileUpload(@RequestPart("user") User user, @RequestPart("file") MultipartFile file)

并将请求更改为这样的东西将起作用:

curl -i -X POST -H "Content-Type: multipart/form-data" \
-F 'user={"name":"John","age":12};type=application/json' \
-F "file=@myfile.txt" http://localhost:8080/post

仅供consumes使用MediaType.MULTIPART_FORM_DATA_VALUE

为了在角度上提出上述类型的请求,可以这样做:

const userBlob = new Blob(JSON.stringify(new User('John', 12)),{ type: "application/json"});
formdata.append('user', userBlob);

Changing

public ResponseEntity<User> handleFileUpload(@RequestParam("user") User user, @RequestPart("file") MultipartFile file)

to

public ResponseEntity<User> handleFileUpload(@RequestPart("user") User user, @RequestPart("file") MultipartFile file)

and changing the request to something like this will work:

curl -i -X POST -H "Content-Type: multipart/form-data" \
-F 'user={"name":"John","age":12};type=application/json' \
-F "file=@myfile.txt" http://localhost:8080/post

For consumes only MediaType.MULTIPART_FORM_DATA_VALUE is required.

To make above kind of request in angular, something like this can be done:

const userBlob = new Blob(JSON.stringify(new User('John', 12)),{ type: "application/json"});
formdata.append('user', userBlob);

相关问答

更多

Spring Boot和Angular(5)项目结构(Spring Boot and Angular (5) project structure)

我一直在把源代码放在你通常期望的地方 - 在'src / main'目录下。 所以,我有src / main / java和src / main javascript,后面的目录中有角度应用程序。 我将角度应用程序设置为src / main / resources / static / ui,并配置SpringBoot应用程序从那里提供服务。 - 附加信息 - 为Angular应用程序的index.html提供服务,我用它: @Bean public WebMvcConfigurerAdapter...

Spring Boot + Angular 2 + JWT(Spring Boot + Angular 2 + JWT)

Response for preflight is invalid (redirect) 这听起来更像是您的服务器没有正确处理飞行前请求。 你在用CORS吗? (即你使用ng serve来运行你的Angular应用程序,但试图访问不同端口/机器上的服务器?)。 因为,基于您所获得的错误,我认为您的后端服务器未设置为正确处理CORS。 Response for preflight is invalid (redirect) That sounds more like your server i...

Spring Boot:如何将JSON对象添加到GET请求?(Spring Boot: How to add JSON Object to GET request?)

您无法直接在请求参数上发送JSON。 你需要像在你想传递给你的服务器的json结构上调用encodeURIComponent()那样做,然后让参数成为一个字符串。 在服务器端,您需要将字符串转换回模型对象。 You can't send JSON on the request parameter, directly. You'll need to do something like call encodeURIComponent() on the json structure you want t...

angular 5在POST请求中获取错误。(angular 5 Getting an error on POST request. Sending header param not works)

尝试这个: 请像这样导入HttpClient和HttpHeaders : import { HttpClient, HttpHeaders } from '@angular/common/http'; 并注入你的班级: constructor(private http: HttpClient) { } 和你的方法是这样的: public getAppData(countryPath):Observable<any>{ let headers: HttpHeaders = new ...

通过Angular 2和JSON发送对象到Spring-Boot的RestController(Sending objects to Spring-Boot's RestController Via Angular 2 and JSON)

@Component @Order(Ordered.HIGHEST_PRECEDENCE) public class CorsFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) { HttpServletResponse response = (HttpServletResponse) res; HttpServl...

Http请求。(Http Request. How to get png name? Spring Boot)

除非您将文件名作为原始上传中的附加参数或标题传递,否则无法获取文件名。 HTTP不了解或关心文件系统以及与之相关的任何内容。 You cannot get the filename unless you pass it through as an additional parameter or header in the original upload. HTTP does not know or care about filesystems and anything associated wit...

Angular 2 post请求不发送图像数据(Angular 2 post request not send image data)

我认为问题在于您如何发送文件。 另一个问题的答案可能会对您有所帮助: https : //stackoverflow.com/a/35669598/5049472 I think the problem is how you send your file. This answer in another question might help you: https://stackoverflow.com/a/35669598/5049472

Angular http和spring boot rest服务(Angular http and spring boot rest service)

我想你错过了@RequestBody 。 当您使用$http with data属性时,数据将在request body传递。 $http({ method: 'POST', url: url, data: { stateCd: scope.stateCd, addressExtras: scope.addressExtras, uploadFile: scope.upFile }, 我想,一旦你添加@Request...

使用单个请求发送JSON和图像。(Send JSON and Image with single request. Angular + Spring Boot)

更改 public ResponseEntity<User> handleFileUpload(@RequestParam("user") User user, @RequestPart("file") MultipartFile file) 至 public ResponseEntity<User> handleFileUpload(@RequestPart("user") User user, @RequestPart("file") MultipartFile file) 并将请求更改为...

将HTML5画布图像上传到服务器Angular2 / Spring Boot(Upload HTML5 canvas image to server Angular2/Spring Boot)

事实证明,框架负责在我的画布中渲染内容(Blend4Web)是一个问题。 当我直接从框架提供的方法获取blob对象时,我能够毫无问题地上传文件。 我共享的代码工作正常,因此可以用作参考。 我向那些花时间分析它的人道歉。 It turned out that it is an issue with framework responsible for rendering content in my canvas (Blend4Web). I was able to upload file withou...

相关文章

更多

Object Oriented Programming

Some might also contend that inheritance should be ...

javascript常用对象

本节的主要内容是javascript常用对象,包括Date对象、String对象和Array对象

javascript快速入门

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

javascript 问题

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

JavaScript 事件

作者:李丽媛 联系方式:lly219#gmail.com 日 期:2010-2-26 前言 ...

JavaScript 事件

作者:李丽媛 联系方式:lly219#gmail.com 日 期:2010-2-26 前言 ...

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

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

在main方法中开启线程与@Test中开启线程

用来测试线程同步问题的代码: public class SynchronizeDemo { p ...

请教javascript问题

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

Hadoop 0.21如何运行单个test case

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

最新问答

更多

获取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}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本