Home > Mobile >  How can I create an object with input values and push it to array?
How can I create an object with input values and push it to array?

Time:05-17

Let's say I have the following array in React:

const employees=[
    {
      id:1,
      firstName:'John',
      lastName:'Martinez'
    },
    {
        id:2,
        firstName:'Julio',
        lastName:'Mariella'
    }
]

I want to generate an array from user's input. For example user types their first name and last name in certain input fields and then these values are inserted into array and pushed to the employees object.

I tried to insert array with:

employees.push(employee);

but that's not correct.

CodePudding user response:

If you are using react then you should use state hook like this:

replace the initial array value with your initial array

const [employees, setEmployees] = useState([]);

add the new employee

setEmployees(prevEmployees => ([...prevEmployees, ...newEmployee]));

CodePudding user response:

This is how you do it, but you will have add the ID increment and input yourself but this is how you add to array. This has nothing to do with react, just an example of the code you provided to work, check risay1983 answer for the react help.

 const employees=[
    {
      id:1,
      firstName:'John',
      lastName:'Martinez'
    },
    {
        id:2,
        firstName:'Julio',
        lastName:'Mariella'
    }
]


const idnew = 3;
const newfirst = "David";
const newlast = "Smaith";

const newID = {id: idnew, firstname: newfirst, lastname: newlast};

employees.push(newID);
console.log(employees);
  • Related