对迭代嵌套对象感到困惑

时间:2016-01-05 04:45:21

标签: javascript

所以我有以下对象:

{ err:
  { message: 'Validation failed',
    name: 'ValidationError',
    errors: 
     { username: 
        { properties: [Object],
          message: 'Path `username` is required.',
          name: 'ValidatorError',
          kind: 'required',
          path: 'username',
          value: '' } } } }

我正在尝试迭代err.errors并将示例err.errors.username.message推送到数组中:

for(var error in err.errors){
  messages.push(error.message);
}

这样做只是将null推送到我的messages数组中。因此,为了排查问题,我尝试console.log(typeof error);给了我一个string。这是令人困惑的,因为当我在typeof上调用err.errors.username时,它会输出object,然后在循环内调用它会生成string ...

那么这里发生了什么?

3 个答案:

答案 0 :(得分:2)

  

您正在从key对象object which is another错误. for-in in密钥will return用户名->消息中访问hence you need to access that key from object and then from that用户名`对象。

试试这个:



var obj = {
  err: {
    message: 'Validation failed',
    name: 'ValidationError',
    errors: {
      username: {
        properties: [Object],
        message: 'Path `username` is required.',
        name: 'ValidatorError',
        kind: 'required',
        path: 'username',
        value: ''
      },
      password: {
      properties: [Object],
      message: 'Path `password` is required.',
      name: 'ValidatorError',
      kind: 'required',
      path: 'password',
      value: ''
      }
    }
  }
};
var messages = [];
for (var error in obj.err.errors) {
  messages.push(obj.err.errors[error].message);
}
alert(messages);




Fiddle here

答案 1 :(得分:1)

此处的问题for in会为您提供密钥而非数据尝试for oferr.errors[error]

答案 2 :(得分:1)

尝试迭代-(void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.webView removeObserver:self forKeyPath:@"loading"]; [self.webView removeObserver:self forKeyPath:@"estimatedProgress"]; } -(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil]; [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil]; [self.progressView setProgress:0.0f animated:NO]; if ([self.documentDirectory checkEpubFileIfExistsAtPath:self.epubFolder]) { NSString *filePath = [NSString stringWithFormat:@"%@/%@/%@/OEBPS/%@", [self.documentDirectory getDocumentsDirectory], self.epubFolder, self.epubName, [_html_link substringToIndex:[_html_link rangeOfString:@"#"].location]]; //Loading webview with progress bar action if ([_html_link rangeOfString:@"#"].location != NSNotFound) { self.tag = [_html_link substringFromIndex:[_html_link rangeOfString:@"#"].location]; NSURL *URL = [NSURL fileURLWithPath:filePath]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; [self.webView loadRequest:request]; } } else { NSDictionary *object = [self.alertMessages getMessageObj:@"translationNotAvailable"]; [self presentViewController:[self.alertController alertWithCustomOkayAction:[object objectForKey:@"title"] message:[object objectForKey:@"msg"] callback:^(void) { [self dismissViewControllerAnimated:YES completion:nil]; }] animated:YES completion:nil]; } } //Constraints for Web View - (void) setConstraintsForWebView { [self.webView setTranslatesAutoresizingMaskIntoConstraints:NO]; WKWebView *webView = self.webView; UIProgressView *progressView = self.progressView; UIToolbar *toolBar = self.toolBar; [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-8-[webView]-8-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(webView)]]; [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[progressView]-0-[webView]-[toolBar]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(progressView, webView, toolBar)]]; } - (void)viewDidLoad { [super viewDidLoad]; //Do any additional setup after loading the view. self.alertController = [AlertController new]; self.alertMessages = [AlertMessages new]; self.documentDirectory = [DocumentDirectory new]; self.languageController = [LanguageController new]; //Set observer for webview load self.webView = [[WKWebView alloc] initWithFrame:CGRectZero]; self.webView.navigationDelegate = self; [self.view insertSubview:self.webView belowSubview:self.progressView]; [self setConstraintsForWebView]; } #pragma mark KVO - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"loading"]) { [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:self.webView.loading]; } else if ([keyPath isEqualToString:@"estimatedProgress"]) { self.progressView.hidden = self.webView.estimatedProgress == 1; self.progressView.progress = self.webView.estimatedProgress; } } #pragma mark Web view navigation delegate - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { [self.progressView setProgress:0.0f animated:NO]; if (self.tag) { [self.webView evaluateJavaScript:[NSString stringWithFormat:@"window.location.hash='%@'", self.tag] completionHandler:nil]; } } - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error { [self presentViewController:[self.alertController alertWithAction:@"Error!" message:error.localizedDescription] animated:YES completion:nil]; }



obj.err.errors.username