typescript循环遍历对象并通过转换值来创建新对象

时间:2017-02-09 19:27:07

标签: javascript typescript

给出以下对象,

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'
    ]
  } 
}

3 个答案:

答案 0 :(得分:2)

编写一个小函数来映射对象属性,类似地图,但对于对象。

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])};
};

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

您可以简单地拆分

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[];
}