Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Desctructuring object with object arrays

I have this kind of 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 should have objects consisting only of type and checked values. Need my output to be like below example.

OUTPUT:

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

So far everything I've tried doesn't seem to work.

My last failed attempt:

    Object.keys(tabs).forEach(key =>
      ({
        updatedState: {
          [key]: (({ documentTypeId, checked }) => ({ documentTypeId, checked }))(tabs[key]),
        },
      }),
    );
like image 734
Simas.B Avatar asked Jan 29 '23 19:01

Simas.B


2 Answers

You can use Array.reduce() to iterate the object's keys, with an inner Array.map() and destructuring to create new objects from the properties you want to keep:

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)
like image 161
Ori Drori Avatar answered Jan 31 '23 07:01

Ori Drori


You can use a combination of reduce (to iterate through the object keys) and map (for your children arrays)

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);
like image 43
klugjo Avatar answered Jan 31 '23 07:01

klugjo