简体   繁体   English

如何从嵌套数组创建 object 数组?

[英]How to create array of object from nested array?

I have the following array:我有以下数组:

const a = [{
    Name: 'martha',
    Surname: 'james',
    Type: 'student',
  },
  {
    Name: 'Meredith',
    Surname: 'Napier',
    Type: 'Teacher',
  },
  {
    Name: 'Julie',
    Surname: 'Schrutt',
    Type: 'student',
  }
]

I need to convert in the following format:我需要转换为以下格式:

const a = [{
      Type: 'student',
      Names: [{
          Firstname: 'martha',
          Lastname: 'james'
        },
        {
          Firstname: 'Julie',
          Lastname: 'schrutt'
        }
      ],
    },
    {
      Type: 'Teacher',
      Names: [{
        Firstname: 'meredith',
        Lastname: 'Napier'
      }, ],
    }

I have tried lodash grouping, object.entries, array map, reduce, but not able to figure out how to do it.我尝试过 lodash 分组,object.entries,数组 map,减少,但无法弄清楚如何去做。

You can easily achieve this result using reduce in js.您可以在 js 中使用reduce轻松实现此结果。

 const a = [ { Name: "martha", Surname: "james", Type: "student", }, { Name: "Meredith", Surname: "Napier", Type: "Teacher", }, { Name: "Julie", Surname: "Schrutt", Type: "student", }, ]; const result = a.reduce((acc, curr) => { const { Name, Surname, Type } = curr; const elSearch = acc.find((o) => o.Type === Type); if (elSearch) { elSearch.Names.push({ Firstname: Name, Lastname: Surname, }); } else { acc.push({ Type, Names: [ { Firstname: Name, Lastname: Surname, }, ], }); } return acc; }, []); console.log(result);

You can make the above code snippet shorter if you change the name of the variable while destructuring如果在解构时更改变量的名称,则可以使上述代码片段更短

const { Name: Firstname, Surname: Lastname, Type } = curr;

and use it as并将其用作

elSearch.Names.push({ Firstname, Lastname });

 const a = [ { Name: "martha", Surname: "james", Type: "student"}, { Name: "Meredith", Surname: "Napier", Type: "Teacher"}, { Name: "Julie", Surname: "Schrutt", Type: "student"}, ]; const result = a.reduce((acc, curr) => { const { Name: Firstname, Surname: Lastname, Type } = curr; const elSearch = acc.find((o) => o.Type === Type); if (elSearch) { elSearch.Names.push({ Firstname, Lastname }); } else { acc.push({ Type, Names: [{ Firstname, Lastname }] }); } return acc; }, []); console.log(result);

Using forEach :使用forEach

 const a = [{ Name: 'martha', Surname: 'james', Type: 'student', }, { Name: 'Meredith', Surname: 'Napier', Type: 'Teacher', }, { Name: 'Julie', Surname: 'Schrutt', Type: 'student', } ]; const out = [{Type: 'student', Names: []}, {Type: 'teacher', Names: []}]; a.forEach(a => { if (a.Type === 'student') return out[0].Names.push({ Firstname: a.Name, Lastname: a.Surname, }); out[1].Names.push({ Firstname: a.Name, Lastname: a.Surname, }); }); console.log(out);

Try something like this:尝试这样的事情:

const output = {};    

for(const person of array) {
    if(!output[person.Type]) output[person.Type] = { Type: person.Type, Names:[] };
    output[person.Type].Names.push({ Firstname: person.Name, Lastname: person.Surname });
}

return Object.values(output);

Or in short:或者简而言之:

Object.values(array.reduce((pre, curr) => {
    if(!pre[curr.Type]) pre[curr.Type] = { Type: curr.Type, Names:[] };
    pre[curr.Type].Names.push({ Firstname: curr.Name, Lastname: curr.Surname });
    return pre;
} , {}))

 const a = [{ Name: 'martha', Surname: 'james', Type: 'student', }, { Name: 'Meredith', Surname: 'Napier', Type: 'Teacher', }, { Name: 'Julie', Surname: 'Schrutt', Type: 'student', } ] const types = a.reduce((acc, next) => { if (acc.includes(next.Type)) { return acc } return acc.concat(next.Type) }, []) const arrayByTypes = types.map((type) => { return { Type: type, Names: a.filter(item => item.Type === type).map(filtered => ({ Name: filtered.Name, Surname: filtered.Surname })) } }) console.log(arrayByTypes)

const data = [{
        Name: 'martha',
        Surname: 'james',
        Type: 'student',
    },
    {
        Name: 'Meredith',
        Surname: 'Napier',
        Type: 'Teacher',
    },
    {
        Name: 'Julie',
        Surname: 'Schrutt',
        Type: 'student',
    }
]

function processData(data) {
    finalMap = new Map();
    data.forEach((obj) => {
        let typeName = obj["Type"];
        let firstName = obj["Name"];
        let lastName = obj["Surname"];
        if (!finalMap[typeName]) {
            finalMap[typeName] = [];
        }
        finalMap[typeName].push({
            "Firstname": firstName,
            "LastName": lastName
        });
    });
    let result = [];
    for (const [key, value] of Object.entries(finalMap)) {
        result.push({
            "Type": key,
            "Names": value
        });
    }
    return result;

}
console.log(processData(data));

use this method for any group by:通过以下方式将此方法用于任何组:

 const groupBy = function (list, key) { return list.reduce((finalList, item) => { const group = (finalList[item[key]] = finalList[item[key]] || []) group.push(item) return finalList }, {}) } const a = [{ Name: 'martha', Surname: 'james', Type: 'student', }, { Name: 'Meredith', Surname: 'Napier', Type: 'Teacher', }, { Name: 'Julie', Surname: 'Schrutt', Type: 'student', } ] console.log(groupBy(a, 'Type'))

We can use Array.reduce & Object.values in order to achieve the expected output.我们可以使用Array.reduce & Object.values来实现预期的 output。

 const a = [{Name:'martha',Surname:'james',Type:'student'},{Name:'Meredith',Surname:'Napier',Type:'Teacher'},{Name:'Julie',Surname:'Schrutt',Type:'student'}]; const groupBy = (data, by) => { const result = data.reduce((acc, obj) => { const key = obj[by]; const { Type, Name: Firstname, Surname: Lastname } = obj; acc[key] = acc[key] || { Type, Names: []}; acc[key].Names.push({ Firstname, Lastname }); return acc; }, {}); return Object.values(result); } console.log(groupBy(a, "Type"));
 .as-console-wrapper { max-height: 100%;important; }

We can also use Logical nullish assignment (??=) instead of acc[obj[by]] = acc[obj[by]] || { Type, Names: []}我们也可以使用Logical nullish assignment (??=)代替acc[obj[by]] = acc[obj[by]] || { Type, Names: []} acc[obj[by]] = acc[obj[by]] || { Type, Names: []}

 const a = [{Name:'martha',Surname:'james',Type:'student'},{Name:'Meredith',Surname:'Napier',Type:'Teacher'},{Name:'Julie',Surname:'Schrutt',Type:'student'}]; const groupBy = (data, by) => { const result = data.reduce((acc, obj) => { const key = obj[by]; const { Type, Name: Firstname, Surname: Lastname } = obj; acc[key]??= { Type, Names: []}; acc[key].Names.push({ Firstname, Lastname }); return acc; }, {}); return Object.values(result); } console.log(groupBy(a, "Type"));
 .as-console-wrapper { max-height: 100%;important; }

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

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