Object descent with object arrays

I have this view and object:

obj: {
  child1: [
    { type, checked, text, ... },
    { type, checked, text, ... },
    { type, checked, text, ... },
  ],
  child2: [
    { type, checked, text, ... },
    ...
  ],
  ...
}

I need almost the same object, but child elements must have objects consisting only of types and checked values. My result should be as shown below.

CONCLUSION:

obj: {
  child1: [
    {
      type: "type",
      checked: "checked"
    },
    {
      type: "type",
      checked: "checked"
    },
    {
      type: "type",
      checked: "checked"
    }
  ],
  child2: [
    {
      type: "type",
      checked: "checked"
    }
  ]
}

So far, everything I tried seems to not work.

My last unsuccessful attempt:

    Object.keys(tabs).forEach(key =>
      ({
        updatedState: {
          [key]: (({ documentTypeId, checked }) => ({ documentTypeId, checked }))(tabs[key]),
        },
      }),
    );
+4
source share
2 answers

You can use Array.reduce()to iterate the keys of an object , with internal Array.map()and destructuring to create new objects from the properties that you want to save:

const type = 'type'
const checked = 'checked'
const text = 'text'

const obj = {
  child1: [
    { type, checked, text },
    { type, checked, text },
    { type, checked, text },
  ],
  child2: [
    { type, checked, text },
  ],
}

const result = Object.keys(obj).reduce((r, k) => {
  r[k] = obj[k].map(({ type, checked }) => ({ type, checked }))
  
  return r
}, {})

console.log(result)
Run codeHide result
+6
source

( ) ( )

const obj = {
  child1: [
    { type: 1, checked: true, text: 'aaa'},
    { type: 2, checked: false, text: 'bbb'},
    { type: 3, checked: true, text: 'ccc'}
  ],
  child2: [
    { type: 4, checked: true, text: 'ddd'},
    { type: 5, checked: false, text: 'eee'},
    { type: 6, checked: true, text: 'fff'}
  ]
};

const result = Object.keys(obj).reduce((acc, key) => { 
  acc[key] = obj[key].map(child => 
    ({type: child.type, checked: child.checked}));
    
  return acc;
}, {}); 

console.log(result);
Hide result
+2

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


All Articles