简体   繁体   中英

Group deeply nested values by property keys?

I have the following structure in the app I'm working on:

collection {

   user_entry_1 {
      page_1_id {
         input_1_id: someValue
         input_2_id: anotherValue
      },
      page_2_id {
         ...
      }
   },
   user_entry_2 {
      ...

As you can see, the actual needed values are nested pretty deep. Now I've been fighting for hours on end with how I could group the data, so that the resulting object would look like the following:

collection {

  page_1_id {
    input_1_id: [value1, value2, value3...],
    input_2_id: [value1, value2, value3...]
  },
  page_2_id {
    input_3_id: [value1, value2, value3...],
    ...

If it's any help, I'm dealing with dynamic forms spread over multiple pages. I've tried lodash, writing custom spaghetti-functions using a ton of arrays, etc. but can't simply come up with a clever way to arrange the data like shown above. Basically I need to get the "deepest" nested values into arrays, and the key of each array would be the key of the "input" (multiple same keys, because multiple users).

I've only been coding for a couple years now, so these kinds of array/object manipulations aren't plain vanilla to me. Sorry if it's hard to read or I was unclear.

Here is my attempt:

 const collection = { user_entry_1: { page_1_id: { input_1_id: 'someValue', input_2_id: 'anotherValue' }, page_2_id: { input_3_id: 'someValue' //, //, enter other data here: } }, user_entry_2: { page_1_id: { input_1_id: 'someValue', input_2_id: 'anotherValue' }, page_2_id: { input_3_id: 'someValue' //, //, enter other data here: } } }; //ENTER THE CODE YOU TRIED HERE:

As you can see my output is this:

//Enter output from your attempt:

But I expect:

//Enter desired output:

You can do this with reduce function.

 var collection = { 'user_entry_1': { 'page_1_id': { 'input_1_id': 'someValue 1', 'input_2_id': 'anotherValue' }, 'page_2_id': { 'input_1_id': 'someValue 2', 'input_2_id': 'anotherValue' }}, 'user_entry_2': { 'page_1_id': { 'input_1_id': 'someValue 2', 'input_2_id': 'anotherValue 2' }, 'page_2_id': { 'input_1_id': 'someValue 2', 'input_2_id': 'anotherValue 2' }}}; var result = Object.entries(collection).reduce((acc, [key, value])=>{ for(const [k, v] of Object.entries(value)){ acc[k] = acc[k] || {}; Object.entries(v).forEach(([inputKey, inputValue])=>{ acc[k][inputKey] =acc[k][inputKey] || []; acc[k][inputKey].push(inputValue); }) } return acc; }, {}); console.log(result);

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