0

I am trying to create an object of array. I have defined it as following:

work = {
    'jobs': [{
       'employer': 'ABC',
       'jobPosition': 'FrontEndEngineer',
       'experience': '1 year',
       'city': 'Mumbai'
    }]
};

Since it is an array I am trying to append it to the next position as

work.jobs[1].employer="QWE";
work.jobs[1].jobPosition = "Web Dev Intern";
work.jobs[1].experience = "6 months";
work.jobs[1].city = "Bengaluru";

And consoling the work object, It shows error:

Uncaught TypeError: Cannot set property 'employer' of undefined

What am I doing wrong?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • I am trying to append another object inside the array, instead of replacing it. – Abhishek Rai Jan 08 '17 at 03:14
  • You'll have to set `work.jobs[1] = {};` before you can set its properties. – Jonathan Lonowski Jan 08 '17 at 03:15
  • You should either 1) initialize a new object with the desired properties and append it or 2) create an empty object, append that, and then try the code in your initial post. The problem is that `work.jobs[1]` doesn't exist and is therefore `undefined`. That's why you're getting that error. – Chris Zimmerman Jan 08 '17 at 03:18

3 Answers3

2

try with push:

new_job = {
    'employer': 'QWE',
    'jobPosition': 'Web Dev Intern',
    'experience': '6 months',
    'city': 'Bengaluru'
}

work.jobs.push(new_job)
Mate
  • 4,976
  • 2
  • 32
  • 38
0

work.jobs[1] doesn't exist yet, and is currently undefined. Therefore, accessing it's .employer property throws the error. Use this to initialize work.jobs[1]:

work.jobs[1] = {
    'employer': 'QWE',
    ...
};

or,

work.jobs.push({
    'employer': 'QWE',
    ...
});

var work = {
  'jobs': [{
    'employer': 'ABC',
    'jobPosition': 'FrontEndEngineer',
    'experience': '1 year',
    'city': 'Mumbai'
  }]
};


work.jobs.push({
  'employer': 'QWE',
  'jobPosition': 'Web Dev Intern',
  'experience': '6 months',
  'city': 'Bengaluru'
});

console.log(work);
John Bupit
  • 10,406
  • 8
  • 39
  • 75
0

You can use the Array.prototype.push method. This lets you push the entire defined object instead of adding by deep referencing.

let work = {
    'jobs': [{
       'employer': 'ABC',
       'jobPosition': 'FrontEndEngineer',
       'experience': '1 year',
       'city': 'Mumbai'
    }]
};

const job = {
  'employer': 'QWE',
  'jobPosition': 'Web Dev Intern',
  'experience': '6 months',
  'city': 'Bengaluru'
};

work.jobs.push(job);

console.log(work);
// jobs: Array
// 0: {employer: "ABC", jobPosition: "FrontEndEngineer", experience: "1 year", city: "Mumbai"}
// 1: {employer: "QWE", jobPosition: "Web Dev Intern", experience: "6 months", city: "Bengaluru"}
Akinjide
  • 2,723
  • 22
  • 28