0

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'
  } ] } 
] 
1
  • I made you a snippet. Press F12 and then look in the console why you have an error Commented Nov 2, 2020 at 14:42

2 Answers 2

1

You can't use Array.map because this method return an Array and you are expecting an Object.
just learn about array.reduce and Destructuring assignment

var person  = { firstName:"John",  lastName:"Doe",  rank:0, rollNo:"0201", school:"test",  id:0 }
 ,  person1 = { firstName:"John1", lastName:"Doe1", rank:0, rollNo:"0201", school:"test1", id:1 }
 ;
let testList = [ person, person1 ]

let result = testList.reduce((r,{school, id, ...info})=>
      {
      r[school] = {}
      r[school][id] = {...info, school } 
      return r
      }
      ,{}) 

console.log( result )
.as-console-wrapper { max-height: 100% !important; top: 0; }

for the question update
(and comments part from PO - on chat)

let testList =
      [ { firstName:"John",  lastName:"Doe",  rank:0, rollNo:"0201", school:"test",  id:1 }
      , { firstName:"John1", lastName:"Doe1", rank:0, rollNo:"0201", school:"test1", id:2 }
      , { firstName:"John2", lastName:"Doe2", rank:0, rollNo:"0202", school:"test1", id:3 }
      , { firstName:"John3", lastName:"Doe3", rank:0, rollNo:"0203", school:"test",  id:5 } 
      ]
 ,  result = 
      testList.reduce((res,{ firstName, lastName, rank, rollNo, school })=>
        {
        let line = res.find(x=>x.school===school)
        if (!line) 
          {
          line = { additionalInfo:'', school, randomValue:'', studentInfo:[] }
          res.push(line)
          }
        line.studentInfo.push({ rank, rollNo, firstName, lastName }) 
        return res 
        }
        ,[] ) 

console.log( result )
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for the response. Is it possible to get value of id instead of "id"
Can you please check my recent update in question. Can you please guide me in achieving my desired output.
Sure I will. I am facing a minor issue. If I add "let person2 = { firstName:"John2", lastName:"Doe2", rank:0, rollNo:"0201", school:"test1", id:1 }", output of the function is creating new object in array. My expectation is if I school name is same it should get appended to previous school object instead of creating new object in array
Sure I will wait for your response
|
1

Not 100% sure what all your code with slotObject etc is all about.

But looking at your expected output, it looks like you want to use reduce, with school as a key that you use to reduce into..

eg.

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
};

const r = [person, person1].reduce(
  (a, v) => {
    //extract school & id,
    const {school, id, ...other} = v;
    //lets make sure school exists
    a[school] = a[school] || {};
    //lets add back school to other, and assign
    //and use id as another sub key into school.
    a[school][id] = {...other ,school};
    return a}, 
{});
  
console.log(r);
<h2>JavaScript Objects</h2>

<p id="demo"></p>

3 Comments

Thanks for the response, but this not expected result
@sudhir You wanted the 0: & 1: keys, I've updated to do these.. Also put some comments in there to explain what it's doing.
Awesome. I will go through Java script reduce method. Thanks. I just updated my required output. Can you please guide me to achieve the output using arrays reduce?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.