2017-02-09 39 views
0

考虑下面的对象创建新的对象,打字稿循环,通过变换值

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

我怎么能使用它打字稿/ JavaScript的转换为界面命中的对象?

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

预期结果如下。

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

回答

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

,如果你并不需要一个更通用的解决方案这将工作:

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

谢谢作出回应。不过,我需要更通用的解决方案。 – Rama

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

对不起,不知道你是否读过我的问题,但你的解决方案与我提出的问题无关。 – Rama

+0

你的问题是[键:字符串]:字符串[]行右键可以是任何东西? –

+0

Ofcourse,但是这与分裂接口有什么关系?我不在寻找接口定义。 – Rama