如何添加到对象内的数组

Jor*_*one 0 javascript

我有这个对象,我正在尝试转换它。

names = {
  animals: ['Dog', 'Cat', 'Snake'],
  flowers: ['Rose', 'Daisy']
}
Run Code Online (Sandbox Code Playgroud)

我想把它转换成这样的

newObject = {
  type: ['animals', 'flowers']
  subtype: ['Dog', 'Cat', 'Snake', 'Rose', 'Daisy']
}
Run Code Online (Sandbox Code Playgroud)

我编写了以下函数,但由于某种原因它没有正确填充。

const newObject = {};

Object.keys(names).map(type => {
  newObject['types'] = [...newObject['types'], type];
      names[type].map(subtype => {
        newObject['subtypes'] = [...newObject['subtypes'], subtype];
      })
    })
Run Code Online (Sandbox Code Playgroud)

Nic*_*ons 5

您的.map()回调应该返回您希望每个元素变成的内容,因此回调的行为有点像转换函数。但是,对于这种情况,您不需要使用.map(),只需从对象中提取键和值即可。由于您的值是数组,因此您可以使用.flat()将数组数组合并到一个更大的subtype键值数组中:

const names = {
  animals: ['Dog', 'Cat', 'Snake'],
  flowers: ['Rose', 'Daisy']
}

const type = Object.keys(names);
const subtype = Object.values(names).flat();

const newObject = {type, subtype};
console.log(newObject);
Run Code Online (Sandbox Code Playgroud)