Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript how to format array of object to array of json

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.

like image 585
jones Avatar asked Mar 09 '17 07:03

jones


2 Answers

Just add this to your attachment.josn:

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

and no need to loop the data.

like image 82
Mobasher Fasihy Avatar answered Sep 18 '22 00:09

Mobasher Fasihy


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 ?

like image 34
Bruno Grieder Avatar answered Sep 19 '22 00:09

Bruno Grieder