1

Given the following Object,

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

how can I transform it to an object of the interface Hit using typescript/javascript?

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

Expected result is as follows.

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

3 Answers 3

2

Write a little function which maps object properties, sort of like map, but for objects.

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

Then apply this to your fields property:

function transform(obj): Hit {
  const {id, fields} = obj;

  return {id, fields: map(obj.fields, x => [x])};
};
Sign up to request clarification or add additional context in comments.

Comments

1

This will work if you don't need a more generic solution:

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

1 Comment

Thank You for responding. I need a more generic solution though.
0

You can simply split

export interface Hit {
  id: string;
  fields: Field;
}

export interface Field {
  [index: string]:string[];
}

Inspired from below answer you can see at 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[];
}

4 Comments

Sorry, not sure if you read my question, but your solution is irrelevant to the question I asked.
your problem is [key: string]: string[] line right where key can be anything ?
Ofcourse, but what does that have any thing to do with splitting the interface? I'm not looking for an interface definition.
try to get some hints from the link I shared. you can create a wild card there. its just reference. if it does not help try something else

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.