Home > Software design >  How to make and push object into array inn react Javascript?
How to make and push object into array inn react Javascript?

Time:07-14

I have one object and I want to push it into an state array.

const [values, setValues] = useState([]);

I am getting the array like that:

['abc']

I want to make abc as:

[{Books: 'abc'}, {Books: 'bcd'}]

How can I be able to do this in react? I am getting an error again and again that map is not a function.

CodePudding user response:

you can do this

const arr=['abc','bcd'];

setValues(o=>[...o,...arr.map(i=>({Books:i}))])

CodePudding user response:

This is an example you can update your state with _result variable, it works!

const arr = ['abc', 'def'];
const _result = arr.map(item => {
  return{ Books: item }
});
console.log(_result);

  • Related