Friday, March 17, 2017

TypeScript how to format array of object to array of json

Leave a Comment

I have posted data like _attachments variable: enter image description here

I want to prepare that data to insert as the following structure:

"_attachments": [   {     "container": "string",     "fileName": "string",     "name": "string",     "mime": "string",     "size": 0   } ] 

But what i have done:

for(let key in _attachments) {   job._attachments[key]['container']  = _attachments[key]['container'];   job._attachments[key]['fileName']  = _attachments[key]['fileName'];   job._attachments[key]['name']      = _attachments[key]['name'];   job._attachments[key]['mime']      = _attachments[key]['mime'];   job._attachments[key]['size']      = _attachments[key]['size']; } 

give this error:

 Unprocessable Entity 

Note: I'm using loopback.

4 Answers

Answers 1

Just add this to your attachment.josn:

"id": {   "type": "string",   "id": true,   "defaultFn": "uuid" } 

and no need to loop the data.

Answers 2

From the screen shot _attachments seems to be an array; if that is that case you should not use for...in to iterate over it but for..of. for..in will return all enumerable properties including potentially "unwanted" ones

See the bottom of this excellent MDN resource for details (for..of is available in Typescript)

for (let index of _attachments) { ... } 

Even better, use a map

const result  = _attachments.map( att => ...) 

Also the structure you map to seem identical to the original structure, why not use a direct assignment ?

Answers 3

You need to Stringify it.

Code

data = {      container: "Stuff" }  var jsonString = JSON.stringify(data);   console.log(jsonString); 

Before

enter image description here

After

enter image description here

This is more what your data looks like,

enter image description here

Answers 4

JSON.stringify will help you to get object in json format and JSON.parse will convert back from JSON to object.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment