【问题标题】:typescript loop through object and create a new object by transforming the values打字稿循环遍历对象并通过转换值创建一个新对象
【发布时间】:2017-02-09 19:27:07
【问题描述】:

给定以下对象,

const document = {
  id: 'f8bbe6dd-25e3-464a-90e2-c39038d030e5',
  fields:   {
    lastname: 'TestLastName',
    firstname: 'TestFirstName' 
  } 
}

如何使用 typescript/javascript 将其转换为界面 Hit 的对象?

export interface Hit {
  id: string;
  fields: { [key: string]: string[] };
}

预期结果如下。

document = {
  id: 'f8bbe6dd-25e3-464a-90e2-c39038d030e5',
  fields:   {
    lastname: [
      'TestLastName'
    ],
    firstname: [
      'TestFirstName'
    ]
  } 
}

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    编写一个映射对象属性的小函数,有点像 map,但用于对象。

    type Hash<T> = {[index: string]: T};
    
    function map<T, U>(
      obj: Hash<T>,
      fn: (val: T, prop?: string, obj?: any) => U,
      thisObj?
    ): Hash<U> {
      const result: Hash<U> = {};
    
      Object.keys(obj).forEach(key => result[key] = fn.call(thisObj, obj[key], key, obj));
    
      return result;
    }
    

    然后将其应用于您的 fields 属性:

    function transform(obj): Hit {
      const {id, fields} = obj;
    
      return {id, fields: map(obj.fields, x => [x])};
    };
    

    【讨论】:

      【解决方案2】:

      如果您不需要更通用的解决方案,这将起作用:

      newDocument = {id: document.id, fields: {lastname: [document.fields.lastname], firstname: [document.fields.firstname]} }
      

      【讨论】:

      • 感谢您的回复。不过我需要一个更通用的解决方案。
      【解决方案3】:

      你可以简单的拆分

      export interface Hit {
        id: string;
        fields: Field;
      }
      
      export interface Field {
        [index: string]:string[];
      }
      

      您可以在another stachoverflow answer看到以下答案的启发

      export interface IMeta{}
      export interface IValue{}
      export interface IFunkyResponse {
           [index: string]:IValue[];
      }
      export interface IResponse {
           meta: IMeta;
      }
      
      export class Response implements IResponse {
          meta:IMeta;
          values:IValue[];
          books:IValue[];
          anything:IValue[];
      }
      

      【讨论】:

      • 抱歉,不确定您是否阅读了我的问题,但您的解决方案与我提出的问题无关。
      • 你的问题是 [key: string]: string[] line right where key can be any ?
      • 当然,但这与拆分界面有什么关系?我不是在寻找接口定义。
      • 尝试从我分享的链接中获得一些提示。你可以在那里创建一个通配符。它只是参考。如果它没有帮助尝试其他的东西
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 2016-11-22
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      相关资源
      最近更新 更多