2

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,

1
  • 2
    newArray[0].time = 30 Commented Apr 11, 2019 at 14:30

3 Answers 3

2

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)

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

Comments

1

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

Comments

0

Does the follwoing work for you:

projects[0].time = 30;
console.log(projects);

Comments

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.