Reputation: 55
I have an array of Objects.
{projectId:10,projectName:design,status:done},
{projectId:11,projectName:code,status:onGoing}
Now, this array is coming from an API call and its dynamic.
I want to insert an item, {time:30}
into the first object in the array.
That is, into the object with the index 0.
So, the output will be like this.
{projectId:10,projectName:design,status:done,time:30},
{projectId:11,projectName:code,status:onGoing}
I have tried the following code:
let projects = [{projectId:10,projectName:design,status:done},
{projectId:11,projectName:code,status:onGoing} ];
let newArray = projects.slice();
newArray[0].push({ time: '30' });
console.log(newArray);
But the above code is giving me the following error.
TypeError: newArray[0].push is not a function
Can you help me out with this problem. Thanks,
Upvotes: 2
Views: 2503
Reputation: 765
Does the follwoing work for you:
projects[0].time = 30;
console.log(projects);
Upvotes: 0
Reputation: 12960
Element at index 0 is an Object, push() is a method of Array prototype.
You can use the method as shown below.
let projects = [{projectId:10, projectName: 'design' ,status: 'done'},
{projectId:11,projectName:'code',status:'onGoing'} ];
projects[0].time = 30
console.log(projects)
Upvotes: 2
Reputation: 36574
You can't push()
to an object. set time
property of the item the 0
index
newArray[0].time = '30'
You can also use Object.assign()
Object.assign(newArray[0],{time:'30'});
Upvotes: 1