TypeScript how to format an array of an object into a json array

I published data like _attachments : enter image description here

I want to prepare this data for insertion as the following structure:

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

But what I did:

 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']; } 

enter this error:

  Unprocessable Entity 

Note. I am using loopback.

+6
source share
4 answers

Just add this to your attachment.josn :

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

and no need to loop data.

+4
source

_attachments array is presented from the _attachments screenshot; If so, you should not use for...in to repeat, but for..of . for..in returns all enumerated properties, including potentially "unwanted"

For more details see the excellent MDN resource below ( for..of is available in Typescript)

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

Better yet, use a card.

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

Also, the structure that you look on the map is identical to the original structure, why not use the direct assignment?

+3
source

You need Stringify.

the 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 like your data,

enter image description here

0
source

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

0
source

Source: https://habr.com/ru/post/1015604/


All Articles