我有以下带有4个对象的数组:
var btnObj = [
{sect_title: 'Navigation', btn_title: 'Übersicht'},
{sect_title: 'Navigation', btn_title: 'Inhaltsverzeichnis'},
{sect_title: 'Modul 1', btn_title: 'Lehrwerk'},
{sect_title: 'Modul 1', btn_title: 'Prinzipien'},
]
2个不同的节标题中每个都应具有2个btn标题,从而导致:
var btnObjResult = [
"Navigation" = [
{btn_title: 'Übersicht'},
{btn_title: 'Inhaltsverzeichnis'},
],
"Modul 1" = [
{btn_title: 'Lehrwerk'},
{btn_title: 'Prinzipien'},
]
]
我只是不知道如何在JS中完成此操作。非常感谢您提供任何提示。
答案 0 :(得分:1)
我猜这就是您要寻找的东西:
var btnObj = [
{sect_title: 'Navigation', btn_title: 'Übersicht'},
{sect_title: 'Navigation', btn_title: 'Inhaltsverzeichnis'},
{sect_title: 'Modul 1', btn_title: 'Lehrwerk'},
{sect_title: 'Modul 1', btn_title: 'Prinzipien'},
]
const transformedObj = btnObj.reduce((obj, {sect_title, ...rest}) => {
if(!(sect_title in obj)) obj[sect_title] = [];
obj[sect_title].push(rest);
return obj;
}, {});
console.log(transformedObj);
答案 1 :(得分:1)
let btnObj = [
{sect_title: 'Navigation', btn_title: 'Übersicht'},
{sect_title: 'Navigation', btn_title: 'Inhaltsverzeichnis'},
{sect_title: 'Modul 1', btn_title: 'Lehrwerk'},
{sect_title: 'Modul 1', btn_title: 'Prinzipien'},
]
let myData = {}; //if you need in array you can use myData = [];
btnObj.forEach((d)=>{
if(!myData[d.sect_title]) myData[d.sect_title] = [];
myData[d.sect_title].push({btn_title:d.btn_title})
})
console.log(myData);