0

Hi every one I have two JSON string

[{desc:"john",number:"22",designation:"manager"}]

another JSON string

[{name:"creek",ID:"198",role:"developer"}]

so i need to map first JSON file with second JSON file

my output should be like this

[{desc:"creek",number:"198",designation:"developer"}]

so here i thought while converting our JSON string to JAVASCRIPT object only we need to replace the attributes..

can any one help me with this Thanks...

john
  • 1
  • 1
  • 1
    So, what did you try? Can you post your code on https://jsfiddle.net or something? – Dale Nguyen Jun 17 '18 at 22:27
  • See [How can I merge properties of two JavaScript objects dynamically?](https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – xmojmr Jun 18 '18 at 07:04

1 Answers1

0

You have two distinct types, which we can define typescript types for.

type FormatOne = {
  desc: string;
  number: string;
  designation: string;
}

type FormatTwo = {
  name: string;
  ID: string;
  role: string;
}

We can create a function to map from one type to the other.

const twoToOne = ({name, ID, role}: FormatTwo): FormatOne => ({
  desc: name,
  number: ID,
  designation: role,
})

When parsing JSON from a string, you have to assert the type with as because typescript does not know what the type will be. We can say that it will be an array with a mix of both types.

const str = '[{desc:"john",number:"22",designation:"manager"}, {name:"creek",ID:"198",role:"developer"}]';
const arr = JSON.parse(str) as Array<FormatOne | FormatTwo>;

If you know that you have an array of all FormatTwo then reformatting it is as simple as calling array.map(twoToOne).

When you have a mixed array, we need to check each element and conditionally call the converter. We use 'name' in item as a type guard to see if the item is FormatTwo.

const fixed = arr.map( item => 
  ('name' in item) ? twoToOne(item) : item
);

This new array fixed has the type FormatOne[] with no assertions required.

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102