简体   繁体   English

使用 2 个列表创建 map,其中键是字符串,值是对象数组

[英]Create a map using 2 lists where the keys are strings and values are array of objects

I have the following where I am adding objects into an array based on the catType value.我有以下内容,我根据catType值将对象添加到数组中。
This works fine.这工作正常。 But is there a way I could have written this more elegantly?但是有没有办法让我写得更优雅?
Possibly combining the steps plus without having to create empty arrays for the map at the start.可能结合步骤加上不必在开始时为 map 创建空的 arrays。

const cats = ['cat1', 'cat2']

let newMap = {};
// initialise map with values from above array as keys and values as empty arrays 
cats.forEach(category => {
    newMap[category.title] = [];
});

// list of objects
const newList = [
    {
        catType: 'cat1',
        name: 'name1'
    },
    {
        catType: 'cat2',
        name: 'name2'
    },
    {
        catType: 'cat1',
        name: 'name3'
    },
    {
        catType: 'cat2',
        name: 'name4'
    },
    {
        catType: 'cat1',
        name: 'name5'
    }
]

// add each object to a list in above map based on the `catType` value
newList.forEach(detail => {
    newMap[detail.catType].push(detail);
});

Expected outcome预期结果

{
    cat1: [
        {
            catType: 'cat1',
            name: 'name1'
        },
        {
            catType: 'cat1',
            name: 'name3'
        },
        {
            catType: 'cat1',
            name: 'name5'
        }
    ],
    cat2: [
        {
            catType: 'cat2',
            name: 'name2'
        },
        {
            catType: 'cat2',
            name: 'name4'
        }
    ],
}

To note:要注意:

I have looked at another prior question with some answers.我已经查看了另一个先前的问题并给出了一些答案。
The answers in there is not what I am looking for.那里的答案不是我想要的。
This is to achieve a map where the keys are strings and values are array of objects.这是为了实现 map,其中键是字符串,值是对象数组。
And the data is obtained from 2 lists (newList and cats).并且数据是从 2 个列表(newList 和猫)中获得的。
This is the past question for reference.这是过去的问题,供参考。
https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects

Simple sort, nothing fancy here.简单的排序,这里没什么特别的。

 // list of objects const newList = [ { catType: 'cat1', name: 'name1' }, { catType: 'cat2', name: 'name2' }, { catType: 'cat1', name: 'name3' }, { catType: 'cat2', name: 'name4' }, { catType: 'cat1', name: 'name5' } ] let cats1 = []; let cats2 = []; var sortCats = () => { for(let listItem of newList) { if (listItem.catType === "cat1") cats1.push(listItem); if (listItem.catType === "cat2") cats2.push(listItem) } } sortCats(); let obj = { cat1: cats1, cat2: cats2 } console.log(obj);

Since it seems like all cats are mentioned again as catType properties:因为似乎所有的cats都被再次提到为catType属性:

newList.reduce((acc, curr) => {
  if (acc.hasOwnProperty(curr.catType)) {
    acc[curr.catType].push(curr);
  } else {
    acc[curr.catType] = [curr];
  }

  return acc;
}, {});

Which, yeah, is just a groupBy.是的,这只是一个 groupBy。 Abstract away the field by which the grouping is supposed to happen and you got yourself a groupBy fn:抽象出应该进行分组的字段,然后您就得到了一个groupBy fn:

let groupBy = (array, field) => {
  return array.reduce((acc, curr) => {
    if (acc.hasOwnProperty(curr[field]) {
      acc[curr[field]].push(curr);
    } else {
      acc[curr[field]] = [curr];
    }

    return acc;
  }, {});
}

groupBy(newList, 'catType');

Bonus points if you do everything without mutation, but that's out of scope for this answer.如果您在没有突变的情况下做所有事情,那么奖励积分,但是对于这个答案,这超出了 scope 的范围。

here's one way:这是一种方法:

const cats = ['cat1', 'cat2']
const newList = [
    { catType: 'cat1', name: 'name1' },
    { catType: 'cat2', name: 'name2' },
    { catType: 'cat1', name: 'name3' },
    { catType: 'cat2', name: 'name4' },
    { catType: 'cat1', name: 'name5' }
]

cats.map(c => {return {[c]: newList.filter(nl => nl['catType'] === c)}})

=> [
    {
      cat1: [
        {catType: "cat1", name: "name1"},
        {catType: "cat1", name: "name3"},
        {catType: "cat1", name: "name5"}
      ]
    },  
    {
      cat2: [
        {catType: "cat2", name: "name2"},
        {catType: "cat2", name: "name4"}
      ]
    }   
]   

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

相关问题 如何从一个对象创建一个字符串数组,其中各个键的值是单独的字符串数组? - How do I create an array of strings from an object where the values of individual keys are separate arrays of strings? 将数组映射到对象,使用数组值作为键 - Map an array to an object, using array values as keys .map 数组由其对象键然后。map 每个键的值 - .map array by its objects keys then .map each key for values Javascript 重新格式化或 map 将对象数组转换为新对象数组? 就像重新格式化它并为值提供新的键(名称) - Javascript reformat or map an array of objects to a new array of new objects? like reformating it and giving new keys (names) for values 映射对象数组中的值 - Map values in array of objects 使用字符串数组创建嵌套函数的对象以形成对象键 - Create a object of nested functions using an array of strings to form the object keys JS用键创建对象但没有值 - JS create objects with keys but no values 如何在可以有多个新生成的键的对象数组中对等效键的值求和? - How to sum values of equivalent keys in an array of objects where there can be multiple, newly generated keys? 根据值将键映射到数组 - Map keys into array according to values Jquery映射数组键和值 - Jquery Map Array Keys and Values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM