2

I want to transform my data from one json structure to another. What is the best way to do it?

Here is my original resource (customer) structure is:

{
  "id": "123",
  "data": {
    "name": "john doe",
    "status": "active",
    "contacts": [
      {
        "email": "[email protected]"
      },
      {
        "phone": "12233333"
      }
    ]
  }
}

I want to change it to:

{
  "id": "123",
  "name": "john doe",
  "status": "active",
  "contacts": [
    {
      "email": "[email protected]"
    },
    {
      "phone": "12233333"
    }
  ]
}

Keeping in mind that I might have an array of resources(customers) being returned in GET /customers cases. I want to change that to an array of new data type.

3 Answers 3

4

If customer object is array of object then below will help you to get desire format result

var result = customerObj.map(x => {
  return {
    id: x.id,
    name: x.data.name,
    status: x.data.status,
    contacts: x.data.contacts
  };
});
Sign up to request clarification or add additional context in comments.

Comments

2

here I have used Object.assign() it will be helpful to you

var arr={
  "id": "123",
  "data": {
    "name": "john doe",
    "status": "active",
    "contacts": [
      {
        "email": "[email protected]"
      },
      {
        "phone": "12233333"
      }
    ]
  }
}
arr=Object.assign(arr,arr.data);
delete arr['data'];
console.log(arr);

1 Comment

Acutely, that cood is cleaner than myin
0

You have to Json.parse the json into variable, and then loop through the array of objects, changes the object to the new format, and then JSON.stringify the array back to json.

Example code

 function formatter(oldFormat) {
    Object.assign(oldFormat, oldFormat.data);
    delete oldFormat.data;
}

let parsedData = JSON.parse(Oldjson);

//Take care for array of results or single result 
if (parsedData instanceof Array) {
    parsedData.map(customer => formtter(customer));
} else {
    formatter(parsedData);
}

let newJson = JSON.stringify(parsedData);
console.log(newJson);

Edit

I made the formatter function cleaner by using Kalaiselvan A code

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.