I am new to Javascript.
I am working on converting list of objects to map of maps using javascript.
Below is the code I have written.
var person = {
firstName: "John",
lastName: "Doe",
rank: 0,
rollNo: "0201",
school: "test",
id: 0
};
var person1 = {
firstName: "John1",
lastName: "Doe1",
rank: 0,
rollNo: "0201",
school: "test1",
id: 1
};
var testList = []
var testList1 = []
var slotObject = {}
var slotObjectMap = {};
var finalObject = {};
testList.push(person);
testList.push(person1);
console.log(testList);
for (let i = 0; i < testList.length; i++) {
slotObject["firstName"] = testList[i].firstName;
slotObject["lastName"] = testList[i].lastName;
slotObject["rollNo"] = testList[i].rollNo;
slotObject["rank"] = testList[i].rank;
slotObject["school"] = testList[i].school;
testList1.push(slotObject);
if (finalObject[testList[i]]) {
console.log("yes");
slotObjectMap = {};
} else {
slotObjectMap = finalObject[testList[i].school];
}
slotObjectMap[testList[i].id] = slotObject;
finalObject[testList[i].school] = slotObjectMap;
}
console.log(slotObjectMap);
console.log(finalObject);
// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName;
<h2>JavaScript Objects</h2>
<p id="demo"></p>
My expected output is:
{ test:{
0:{firstName: "John", lastName:"Doe", rank:0, rollNo:"0201", school:"test"},
},
test1:{
1:{firstName: "John1", lastName:"Doe1", rank:0, rollNo:"0201", school:"test1"}
}
}
My above code is not working as expected. Not sure where things are going wrong.
Please help.
My eventual goal is to covert above objects(person, person1) in to below output. Is this is possible using arrays reduce?
[ { additionalInfo : ''
, school : 'test'
, randomValue : ''
, studentInfo:
[ { rank : 0
, rollNo : '0201'
, firstName : 'John'
, lastName : 'Doe'
} ] }
, { additionalInfo : ''
, school : 'test1'
, randomValue : ''
, studentInfo:
[ { rank : 0
, rollNo : '0201'
, firstName : 'John1'
, lastName : 'Doe1'
} ] }
]