将 1 个对象数组转换为嵌套的对象数组

Converting 1 array of objects into a nested array of array of objects

假设我有这个:

var arr = [
    {type:"orange", title:"First"},
    {type:"orange", title:"Second"},
    {type:"banana", title:"Third"},
    {type:"banana", title:"Fourth"}
];

我想谈谈这个。

[[{type:"orange", title:"First"},
{type:"orange", title:"Second"}],

[{type:"banana", title:"Third"},
{type:"banana", title:"Fourth"}]]

为了达到这个目的,我已经看到了很多:

{orange: 
[[{type:"orange", title:"First"},
{type:"orange", title:"Second"}], 
banana: 
[{type:"banana", title:"Third"},
{type:"banana", title:"Fourth"}]}

但这对我的情况没有帮助,我需要它是数组中的数组。 任何帮助将不胜感激

再多一步,您可以将其映射到您想要的格式。

var arr = [
    {type:"orange", title:"First"},
    {type:"orange", title:"Second"},
    {type:"banana", title:"Third"},
    {type:"banana", title:"Fourth"}
];


const typeDictionary = {}

for (item of arr) {
  if (!typeDictionary[item.type]) {
    typeDictionary[item.type] = [item]
  } else {
    typeDictionary[item.type].push(item)
  }
}

// This is the final missing step
const finalResult = Object.values(typeDictionary)

console.log('finalResult', finalResult)

finalResult [
  [
    { type: 'orange', title: 'First' },
    { type: 'orange', title: 'Second' }
  ],
  [
    { type: 'banana', title: 'Third' },
    { type: 'banana', title: 'Fourth' }
  ]
]

你可以使用这个策略

  • 找到所有唯一类型,['orange','banana']
  • 对于每个唯一类型Array#filter原始数组
  • 完成

const input = [
    {type:"orange", title:"First"},
    {type:"orange", title:"Second"},
    {type:"banana", title:"Third"},
    {type:"banana", title:"Fourth"}
];

const output = [...new Set(input.map(o => o.type))]
    .map( type => input.filter(o => o.type === type) )

console.log( output );

或者,您可以按如下方式使用 Array#reduce

const input = [
    {type:"orange", title:"First"},
    {type:"orange", title:"Second"},
    {type:"banana", title:"Third"},
    {type:"banana", title:"Fourth"}
];

const output = input.reduce((prev, {type,title}) => {
    let x = prev.findIndex(ar => ar[0].type === type);
    if( x > -1 ) {
        prev[x].push({type,title});
    } else {
        prev.push([{type,title}])
    }
    return prev;
}, []);
    

console.log( output );