I have parsed the array of json object into a particular format but i need the "type" property value of object to to be dynamic based on condition.
input >>
[
{
"accident_description": "bike accident",
"reported_by": "john",
},
{
"accident_description": "car accident",
"reported_by": "sam",
}
]
output >>
"fields": [
{
"title": "accident_description",
"values": "bike accident"
"type": "generic",
},
{
"title": "reported_by",
"values": "john",
"type": "generic",
},
{
"title": "accident_description",
"values": "car accident"
"type": "generic",
},
{
"title": "reported_by",
"values": "sam",
"type": "generic",
},
]
I have tried this and it is working fine
const arr = [ { "accident_description": "bike accident", "reported_by": "john", }, { "accident_description": "car accident", "reported_by": "sam", } ];
let res = arr.flatMap(x => (Object.entries(x).map(([k,v]) => ({title:k,values:v,type:"generic"}))));
console.log(res);
but here type is fixed ,i need "type" value to dynmaic based on the condition given below.
if(title=='accident_description')
type:generic
else
type:custom
1 Answer 1
Just use a ternary operator. Instead of
{title:k,values:v,type:"generic"}
do
{title:k,values:v,type:(title=='accident_description') ? 'generic' : 'custom'}
In cases where the logic is more complicated than a simple conditional, bear in mind that the arrow function which you've used in map
can have arbitrary code in the body, so you can do any calculations you need and return
the final type
value you want.
2 Comments
type:(title=='value1' || title=='value2') ? 'generic' : 'custom'