微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何按给定字段重新组合对象数组

如何解决如何按给定字段重新组合对象数组

我已经给出了对象数组,就像这样

timestamp

我需要按现场作业过滤的数组数组

const data = [
    {id: 1,name: 'Alex',job: 'IT'},{id: 2,name: 'Pavel',{id: 3,name: 'Joe',{id: 4,name: 'Josh',{id: 5,name: 'Max',job: 'teacher'},{id: 6,name: 'Sam',job: 'teacher'}
]

我试过了,但这不是我想要的

const result = [
    {job: 'IT',workersInfo: [
    {id:1,name:'Alex'},{id:2,name:'Pavel'},{id:3,name:'Joe'},{id:4,name:'Josh'}
    ]
    },{job: 'teacher',workersInfo: [
    {id:5,name: 'Max'},{id:6,name: 'Sam'}
    ]  
    }
]

如何添加新的关键工作人员信息并将信息推送到此字段

解决方法

如果您在每次迭代时创建一个新对象而不是数组,则可以使用 Object.values

const data = [
  {id: 1,name: 'Alex',job: 'IT'},{id: 2,name: 'Pavel',{id: 3,name: 'Joe',{id: 4,name: 'Josh',{id: 5,name: 'Max',job: 'teacher'},{id: 6,name: 'Sam',job: 'teacher'}
];

const groupList = data.reduce((acc,{ job,id,name }) => {
  acc[job] = acc[job] || { job,workersInfo: [] };
  acc[job].workersInfo.push({ id,name });
  return acc;
},{})


console.log(Object.values(groupList));

,

示例如下

const data = [
  { id: 1,name: "Alex",job: "IT" },{ id: 2,name: "Pavel",{ id: 3,name: "Joe",{ id: 4,name: "Josh",{ id: 5,name: "Max",job: "teacher" },{ id: 6,name: "Sam",];

const output = data.reduce((acc,o) => {
  const index = acc.findIndex(a => a.job === o.job);
  if (index !== -1) {
    acc[index].workersInfo.push({ id: o.id,name: o.name });
  } else {
    acc.push({
      job: o.job,workersInfo: [{ id: o.id,name: o.name }],});
  }
  return acc;
},[]);

console.log(output);

,

这样的东西会起作用吗?

const groupBy = function(xs,key) {
     return xs.reduce(function(rv,x) {
     (rv[x[key]] = rv[x[key]] || []).push(x);
     return rv;
  },{});
};

console.log(groupBy(['one','two','three'],'length'));

// => {3: ["one","two"],5: ["three"]}```
,

如果不是像 Array<{job: string,workForce: Array}> 这样的结构,而是像 {[job: string]: Array}

var data = [
    { id: 1,job: 'IT' },job: 'teacher' },job: 'teacher' }
];

var jobs = data.reduce(function (result,person) {
    var jobList = result[person.job];
    if (!jobList) {
        jobList = [];
        result[person.job] = jobList;
    }
    jobList.push(person);
    return result;
},{});

console.log(jobs);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。