我已经分配了一个任务,使用下划线js对角度js中的数据进行分组。
我的JSON:
data = [
{
"Building*": "Building A",
"Wing*": "Wing C",
"Floor*": "Floor 3",
"Room Name*": "Room 3",
"Room Type*": "AC",
"Location*": "Location 1",
"Device ID*": 27,
"Category*": "Soap Hygene",
"Dispenser Name*": "Dispenser 34",
"Type*": "Manual",
"Cartridge Type*": "Type 1",
"Date of installation": "2016-04-11T06:06:22 -06:-30",
"Contact Last Name": "Maynard",
"Email Address": "thomas.boscher@gmail.com",
"Mobile Number with country code": "+1 (949) 590-3465",
"Description": "Description of device",
"Model": 37
},
{
"Building*": "Building B",
"Wing*": "Wing B",
"Floor*": "Floor 3",
"Room Name*": "Room 1",
"Room Type*": "AC",
"Location*": "Location 3",
"Device ID*": 26,
"Category*": "Soap Hygene",
"Dispenser Name*": "Dispenser 33",
"Type*": "Manual",
"Cartridge Type*": "Type 2",
"Date of installation": "2015-07-24T12:42:24 -06:-30",
"Contact Last Name": "Holland",
"Email Address": "thomas.boscher@gmail.com",
"Mobile Number with country code": "+1 (947) 491-2353",
"Description": "Description of device",
"Model": 32
}
]
我需要以下格式的数据,其中每个建筑细节都包含机翼和地板数据
updateData = [{
building: 'Building A' ,
buildingData:[ {
wing: "Wing A",
wingData: [{
floor:'Floor 2',
floorData:[{
room:'Room 3',
roomData:[]
}]
}]
}]
}];
我试过了:
但它失败了。需要帮忙。提前谢谢。
答案 0 :(得分:0)
根据我的理解,您希望以下列嵌套顺序进行groupBy:
建筑 - >>翼 - >>楼层 - >>间
您可以尝试通过传递您想要groupBy的嵌套属性顺序的数组来递归地调用groupBy(或循环遍历您)。请尝试下面的代码段:
const nestedOrder = ['Building*', 'Wing*', 'Floor*', 'Room Name*']
function groupFilter (rawData, attrList) {
if (attrList.length == 0) return rawData
var currentAttr = _(attrList).first()
return _(rawData)
.chain()
.groupBy(currentAttr)
.map((list, attrName) => Object({
[currentAttr]: attrName,
[`${currentAttr}Data`]: groupFilter(list, _(attrList).rest())
}))
.value()
}
console.log(groupFilter(data, nestedOrder))
然后将原始数据压缩到最深的嵌套属性,在这种情况下,“房间名称”,然后您可以编写自定义过滤器以输出您希望RoomData保留的内容。
不确定它是否是正确的方法,但如果运行时不是一个大问题,那么我认为你可以使它正常工作。
希望这对你有所帮助。