Home > Back-end >  How can I push to an array inside of an object
How can I push to an array inside of an object

Time:05-20

I have an object created as follow:

Obj: {
 error:{
  count: 0,
  id :[]
 }
}

I am trying to ad to the list of ids and be able to iterate through the variables in the list of ids, how can you achieve these two goals.

I tried adding using Obj[error].id.push(["123"]), but I can't push more than once. and to view it I tried Obj[error].id and Obj[error].id[0], but it returns the count of the items available in the list instead of the value

I am trying to add values so that it can be

Obj: {
 error:{
  count: 0,
  id :["123","335"]
 }
}

So I would be able to see the values in id and able to add more as needed

CodePudding user response:

This is one way how you can push multiple values into your array:

const da={Obj:{error:{count:0,id:[]}}};

da.Obj.error.id.push(5,2,4,6);

console.log(da);
// and the array alone:
console.log(da.Obj.error.id);

CodePudding user response:

You can do it like this:

const obj = {
    Obj: {
    error:{
      count: 0,
      id :[]
    }
  }
}

const arr = obj.Obj.error.id;
arr.push('123')
arr.push('1234')

for (const i of arr) {
    console.log(i)
}

CodePudding user response:

This will not work:

obj[error].id.push(["123"])

Because error is undefined. You need to either use dot . notation or put quotes around error.

const obj = {
    error: {
        count: 0,
        id: [],
    },
};

// With bracket notation
obj['error'].id.push('123', 'abc');

// With dot notation
obj.error.id.push('321', 'cba');

console.log(obj);

CodePudding user response:

let obj = {
  error: {
    count: 0,
    id: []
  }
};

Adding new elements to the id array

(1) obj["error"].id.push("123")

Notice the quotes around error.
As obj[error] is undefined, hence you have to use quotes around error.

(2) obj.error.id.push("123")

Traversing the id array (using the for loop)

for (let i = 0; i < test.error.id.length; i  ) {
  console.log(obj.error.id[i]);
}
  • Related