如何使用带有角度的打字稿中的动态键访问JSON对象值 [英] How to access JSON object value with dynamic key in typescript with angular

查看:50
本文介绍了如何使用带有角度的打字稿中的动态键访问JSON对象值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用可配置的 targetPath 访问 JSON 对象中存在的值以接收响应.

I want to access value present in JSON object with configurable targetPath for response received.

下面是我的组件类,它将列表中的数据绑定到 HTML 代码中的自动完成下拉

Below is my component class which will bind the data present in list to the autocomplete drop down in HTML code

可配置的键是路径",我想提供该值作为自定义 JSON 对象键字段"中的键.

the configurable key is 'path', which value I want to provide as a key in custom JSON object key 'field'.

import { Component, ViewChild } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { SelectItem } from 'primeng/api';
import { SelectItemGroup } from 'primeng/api';
import { FilterService } from 'primeng/api';
import { AutoComplete } from 'primeng/autocomplete';
import { CountryService } from './countryservice';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  providers: [CountryService, FilterService]
})
export class AppComponent {
  userDetails: any[];

  selectedUserDetails: any[];

  selectedValue: any;

  selectedUserDetail: any;

  path: string = 'contactMedium[0].characteristic.emailAddress';

  testVal: string;

  constructor() {}

  ngOnInit() {
    this.userDetails = [
      {
        id: 'cont-609',
        contactMedium: [
          {
            characteristic: {
              emailAddress: 'test@gmail.com'
            }
          }
        ]
      },
      {
        id: 'cont-610',
        contactMedium: [
          {
            characteristic: {
              emailAddress: 'test@gmail.com'
            }
          }
        ]
      },
      {
        id: 'cont-611',
        contactMedium: [
          {
            characteristic: {
              emailAddress: 'test@gmail.com'
            }
          }
        ]
      },
      {
        id: 'cont-612',
        contactMedium: [
          {
            characteristic: {
              emailAddress: 'test@gmail.com'
            }
          }
        ]
      },
      {
        id: 'cont-614',
        contactMedium: [
          {
            characteristic: {
              emailAddress: 'test@gmail.com'
            }
          }
        ]
      }
    ];
  }

  filterUserDetails(event) {
    const filteredNew: any[] = [];
    this.getUserDetails().then(response => {
      for (let resp of response) {
        this.testVal = resp[this.path];
        filteredNew.push({
          id: resp.id,
          field: resp[this.path]
        });
      }
    });

    this.selectedUserDetails = filteredNew;
  }

  getUserDetails(): Promise<any[]> {
    return Promise.resolve(this.userDetails);
  }

  chooseItem(event) {
    this.selectedUserDetail =
      event.contactMedium[0].characteristic.emailAddress;
  }
}

从从方法 getUserDetails() 收到的响应中,我正在构建一个带有字段id"和字段"的自定义 JSON 对象数组,id 的键是已知的,它本身就是一个id",但字段的键是可配置的就我而言,这是路径.

From the response received from method getUserDetails(), I am building a custom JSON object array with fields 'id' and 'field', the key for id is known which itself is a 'id' but key for field is configurable which is path in my case.

但是看起来上面访问密钥的逻辑没有按预期工作,即我没有得到价值

But looks like above logic where key is accessed is not working as expected i.e I am not getting value for

  filterUserDetails(event) {
    const filteredNew: any[] = [];
    this.getUserDetails().then(response => {
      for (let resp of response) {
        this.testVal = resp[this.path];
        filteredNew.push({
          id: resp.id,
          field: resp[this.path]
        });
      }
    });

    this.selectedUserDetails = filteredNew;
  }

下面是我的 HTML 代码

Below is my HTML code

<h5>Dropdown Testing</h5>
<p>selectedUserDetail : {{selectedUserDetail}}</p>
<p>TestVal : {{testVal}}</p>
<p-autoComplete [(ngModel)]="selectedUserDetail" [suggestions]="selectedUserDetails"
  (completeMethod)="filterUserDetails($event)" [dropdown]="true" field="field">
  <ng-template let-userDetails pTemplate=" item">
    <div>{{userDetails.field}}</div>
  </ng-template>
</p-autoComplete>

如果我像下面那样更改分配的用法,一切正常

If I change the usage of assignment like below everything works fine

字段:resp.contactMedium[0].characteristic.emailAddress

我的代码链接在这里:https://stackblitz.com/edit/primeng-autocomplete-demo-dyihrs?file=src%2Fapp%2Fapp.component.html

这里的期望是将键值:contactMedium[0].characteristic.emailAddress 从 getUserDetails() 接收到自定义 JSON 对象,该对象正在 filterUserDetails() 中构建到字段"键.

Expectation here is to assign value of key: contactMedium[0].characteristic.emailAddress received from getUserDetails() to custom JSON object which is getting build in filterUserDetails() to 'field' key.

推荐答案

您应该意识到您的领域可能非常复杂,但在您提到的情况下,可以通过以下方式解决:

You should be aware that your field can be very complex but in the case you mentioned, can be resolved with this:

resolveField(data: any, field: string): any {
  if (data && field) {
    let fields: string[] = field.split('.');
    let value = data;
    for(let i = 0, len = fields.length; i < len; ++i) {
      if (value == null) {
        return null;
      } else {
        const pos: number = fields[i].match(/\d+/g)?.[0];
        if(pos != null) {
          const property = fields[i].match(/^\w+/g);
          value = value[property][pos];
        } else {
          value = value[fields[i]];
        }
      }
    }
    return value;
  } else {
    return null;
  }
}

您可以将 resolveField 函数用作逻辑的一部分.您可以根据需要或需要对其进行修改,例如:这里仅考虑将字母作为属性名称的一部分.

You can use the resolveField function as part of your logic. You can modify it, as you want or required, for example: here is considering only letters as part of the property names.

这是解决方案 用于您的代码.

这篇关于如何使用带有角度的打字稿中的动态键访问JSON对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆