抓取特定的对象属性,而不是直接引用

时间:2019-04-12 14:44:21

标签: javascript angular typescript

我试图在我的checkForUrgentEvents方法中获取特定的对象属性并返回它。不用引用我当前的方式,而是可以找到特定的属性?我尝试了Object.hasownproperty,但是由于它嵌套得很深,所以无法正常工作。

  private checkForUrgentEvents(urgentEventsData: any, query:CurrentContentParams) {
  return urgentEventsData.data.Data[
      query.type + caasConfig.urgentContentIdSuffix
    ].content[query.id];

  }


// urgentEventsData:

{ status: 200,
  statusText: 'OK',
  headers:
   { connection: 'close',
     'transfer-encoding': 'chunked' },
  config:
   { adapter: [Function: httpAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 0,
     xsrfCookieName: 'XSRF-TOKEN',
     method: 'get',
  data:
   { LatestModified: 1555080079154,
     Results: 1,
     Error: '',
     Data: { faqsurgentcontent: [Object] } } }

//query:
{ id: 'MAIN', type: 'faqs' }

2 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

function findById(o, id) {
    //Early return
    if( o.id === id ){
    return o;
    }
    var result, p; 
    for (p in o) {
        if( o.hasOwnProperty(p) && typeof o[p] === 'object' ) {
            result = findById(o[p], id);
            if(result){
                return result;
            }
        }
    }
    return result;
}

答案 1 :(得分:0)

我遇到了类似的问题,请按照以下步骤操作:

 parseContentResponse(response: any, scope: string, type: string) {
    if (response) {
      return (
        this.getContentObject(
          response,
          ['data', 'Data', `${scope}`, 'content', `${type}`]
        )
      );
    }
    return response;
  }

//then you could look for the key

 private getContentObject(response: any, contentPathArray: Array<string>) {
    return contentPathArray.reduce(
      (obj, key) => (obj && obj[key] !== 'undefined' ? obj[key] : undefined),
      response
    );
  }