简体   繁体   中英

How to extract data from nested json array?

Every time user submits data, I receive it in nested json array of data and I need extract that data.

So, sometimes it can be from to and then in another example from to and so on. ,然后在另一个示例中是从 ,依此类推。

In this way I receive dynamic json array of data for each user submission.

Example of possible json result:

{ 
  question_xx: [ 'Another question?', 'Probably yes' ],
  question_3: [ 'Home origin planet?', 'Mars' ], 
  question_2: [ 'Are you from planet Earth?',   'No' ],  
  question_1: [ 'Home origin Galaxy?', 'Milky Way' ], 
}

I expect output to be:

Home origin Galaxy? Milky Way
Are you from planet Earth? No
Home origin planet? Mars

and so on

You can get the arrays as an array of arrays with Object.values . How you go from there depends on what specifically you're after. To get your output as strings, you can map() over the outer array and join() everything:

 let j = { question_xx: [ 'Another question?', 'Probably yes' ], question_3: [ 'Home origin planet?', 'Mars' ], question_2: [ 'Are you from planet Earth?', 'No' ], question_1: [ 'Home origin Galaxy?', 'Milky Way' ], } // array of arrays let arr = Object.values(j) console.log(arr) // join arrays as strings // join inner arrays with space, outer arrays with new line let strings = arr.map(arr => arr.join(" ")).join(' \\n') console.log(strings) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM