繁体   English   中英

如何添加到 object 中的数组

[英]How to add to an array within an object

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

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

我想把它转换成这样的东西

newObject = {
  type: ['animals', 'flowers']
  subtype: ['Dog', 'Cat', 'Snake', 'Rose', 'Daisy']
}

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

const newObject = {};

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

你的.map()回调应该返回你希望每个元素变成什么,所以回调的行为有点像转换 function。 但是,对于这种情况,您不需要使用.map() ,只需从 object 中提取键和值即可。 由于您的值是 arrays,您可以使用.flat()将 arrays 的数组合并到您的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);

newObject = {
  type: ['animals', 'flowers']
  subtype: [...names.animals, ...names.flowers] 
}

您还可以使用reduce构建新的 object:

 const names = { animals: ['Dog', 'Cat', 'Snake'], flowers: ['Rose', 'Daisy'] }; const res = Object.entries(names).reduce( ({type, subtype}, [key, values]) => ({ type: type.concat(key), subtype: subtype.concat(values) }), { type: [], subtype: [] } // Starting value ); console.log(res);

任何键和值的全局解决方案

使用Object.keysObject.values与 array.reduce array.reduce() :)

 const names = { animals: ['Dog', 'Cat', 'Snake'], flowers: ['Rose', 'Daisy'] } const newObject = { type: Object.keys(names), subtype: Object.values(names).reduce((acc, item)=> [...acc, ...item],[]) } console.log(newObject);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM