具有对象数组的解构对象

Sim*_*s.B 4 javascript destructuring

我有这种和对象:

obj: {
  child1: [
    { type, checked, text, ... },
    { type, checked, text, ... },
    { type, checked, text, ... },
  ],
  child2: [
    { type, checked, text, ... },
    ...
  ],
  ...
}
Run Code Online (Sandbox Code Playgroud)

我需要几乎相同的对象,但子元素应该只包含类型和选中值的对象.需要我的输出如下例所示.

OUTPUT:

obj: {
  child1: [
    {
      type: "type",
      checked: "checked"
    },
    {
      type: "type",
      checked: "checked"
    },
    {
      type: "type",
      checked: "checked"
    }
  ],
  child2: [
    {
      type: "type",
      checked: "checked"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我所尝试过的一切似乎都不起作用.

我上次失败的尝试:

    Object.keys(tabs).forEach(key =>
      ({
        updatedState: {
          [key]: (({ documentTypeId, checked }) => ({ documentTypeId, checked }))(tabs[key]),
        },
      }),
    );
Run Code Online (Sandbox Code Playgroud)

Ori*_*ori 6

您可以使用Array.reduce()迭代对象的键,使用内部Array.map()解构来从要保留的属性创建新对象:

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 Code Online (Sandbox Code Playgroud)