0

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
asked Apr 22, 2019 at 9:51
0

1 Answer 1

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.

answered Apr 22, 2019 at 10:00

2 Comments

thank you for the answer i tried your solution and it is working fine but i also need to compare that actually with another title like title=='value1'||title=='value2' and it is not working.. acn you please help me with like writing a function there for type attribute to get values based on condition . I have to compare title with 2 values.
the code is more or less exactly the same in that case: type:(title=='value1' || title=='value2') ? 'generic' : 'custom'

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.