-1

I am a beginner to JavaScript. i want to create a common key for some values in JavaScript object. For example, in the below code we have a employee name with some tasks assigned to them, so i have created the tasks as nested object. Now i feel that this is looking like a basic level code. is there any way to achieve this effectively?. Also i want to know how to retrieve nested object's value in function.

const taskInfo = [
  {
    name: "john",
    mail: "mailid",
    task1: { taskname: "name", priority: 2, groupname: "name" },
    task2: { taskname: "name", priority: 2, groupname: "name" },
    task3: { taskname: "name", priority: 2, groupname: "name" }
  },
  {
    name: "smith",
    mail: "mailid",
    task1: { taskname: "name", priority: 2, groupname: "name" },
    task2: { taskname: "name", priority: 2, groupname: "name" }
  }
];

Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42
Logeshps
  • 15
  • 4

1 Answers1

0

I believe it could be done something like this:

taskInfo =  [
        {name: 'John Doe', mail:'john@test.com', tasks: [
                {name:'Task1', priority: 1, groupname: 'gName'},
                {name:'Task2', priority: 1, groupname: 'gName1'},
                {name:'Task3', priority: 1, groupname: 'gName2'},
            ]
        },
        {name: 'Susan Doe', mail:'susan@test.com', tasks: [
                {name:'Task4', priority: 1, groupname: 'gName'},
                {name:'Task5', priority: 2, groupname: 'gName2'},
                {name:'Task6', priority: 3, groupname: 'gName2'},
            ]
        }
    ]

To loop through the array have a look at this: Loop through an array in JavaScript

Jon
  • 766
  • 1
  • 9
  • 27
  • yes, i have tried this. but i am facing some issues to retrieve data from the inner array. could you help me on this? – Logeshps Feb 03 '20 at 10:17
  • Try this: taskInfo[0].tasks[0].name – Jon Feb 03 '20 at 10:22
  • i want to retrieve value of priority from inner tasks array and push that into separate empty array. it is kind of destructuring. i have tried using some array.prototype.methods, but end up with undefined error .could you help me on this? – Logeshps Feb 04 '20 at 09:07
  • the value of priority would be: taskInfo[i].tasks[j].priority you just need to assign that value to an array: newArray[] = taskInfo[i].tasks[j].priority (i and j are the temp variables) – Jon Feb 04 '20 at 09:52
  • really sorry..couldn't achieve. should i use nested for loop to get this value...since i am new to javascript couldn't understand. could you provide the sample loop to retrieve the data. – Logeshps Feb 04 '20 at 10:56
  • I edited my answer to include how to loop through an array in JS – Jon Feb 04 '20 at 13:43
  • don't forget to mark the answer as valid if everything is working. – Jon Feb 05 '20 at 13:18