-3

How to use .push array in proper way using javascript?

my code

let persons = [{
    "person1": "person1"
  },
  {
    "person1": "person1"
  }
]

let addPerson = []

addPersn.push({
  "person1": "person2"
})

let allPerson = persons.push(addPerson)
console.log(allPerson)

expected behavior

{
  "person1": "person1"
},
{
  "person1": "person1"
},
{
  "person1": "person1"
}

current result

3

How to use .push array in proper way using javascript?How to use .push array in proper way using javascript?

4
  • You do not need addPersn.push. You can directly push it to persons. However, assuming you are trying to create a setter, you can do this: addPerson = (newPerson) => person.push(newPerson) Commented Nov 28, 2022 at 9:30
  • push returns the new length of the array. Commented Nov 28, 2022 at 9:33
  • At step persons.push(addPerson) you are pushing an array with one person details addPerson in persons array. Thus at the end persons array will have [Person, Person, [Person]] that last element is not object but an array with one object. Instead directly push the object in persons array. Do like this. let newPerson = { "person1": "person2" } , then, persons.push(newPerson) Commented Nov 28, 2022 at 9:35
  • This this out ide.geeksforgeeks.org/61c37f0e-41de-4bcb-b1ef-243d105adacf Commented Nov 28, 2022 at 9:39

1 Answer 1

1

Try this

let persons = [
  {
    person1: "person1",
  },
  {
    person2: "person2",
  },
];

const newPerson = {
    person3: "person3",
}

persons.push(newPerson);
console.log(persons);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.