0

I have a JSON string and want to convert it to a an object in javascript, the only issue is the destination object will have different variable names and i want key to assign to a variable and value to a different variable

The JSON would be

{
 "Value1":"Type1",
 "Value2":"Type2"
}

The object will be

interface Object {
   Value: string;
   Type: string;
}

I want the JSON to be converted to object array where assigning key (Value1/Value2) to object variable Value and value (Type1/Type2) to object variable Type so the resultant object array would look like below

[{Value: Value1, Type: Type1}, {Value: Value2, Type: Type2}]

Regular JSON.parse wouldn't work as the object is different from json string, any help is appreciated.

0

4 Answers 4

2

You can make use of Object.entries and map:

const obj = {
 "Value1":"Type1",
 "Value2":"Type2"
};

const result = Object.entries(obj).map(([Value, Type])=>({Value, Type}));

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

1

You can use this:

Object.entries(JSON.parse(json)).map(([Value, Type]) => {
    return { Value, Type };
});

Comments

0

Refular JSON.parse works just fine, you just need to do a conversion step after parsing. Break the problem down in multiple steps.

type MyInput = {
  Value1: string;
  Value2: string;
}
type MyOutput = {
  Value: string;
  Type: string;
}

function myConversionFunction(input: MyInput): MyOutput {
  return {
    Value: input.Value1,
    Type: input.Value2
  }
}

const out = JSON.parse(str).map(myConversionFunction);

Comments

0

This is a great question that I often run into in other languages.

I find it easiest to create a helper function or constructor that maps the appropriate key to the appropriate variables. You take the keys in as parameters and create the object assigning each key to the correct variable.

You will always be mapping the same key name to the same variable name so if you set this mapping once in this helper method and call it for each object it should work correctly for each of them.

I don't actively code in JS. Maybe you thought of this and a reason it doesn't work well?

Comments

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.