ReactJS: Updating each element of a state array, with a different value

Viewed 50

I would like a little bit of help with the following situation in React JS: I have a state in one of my components which is an array of 3 json objects, like this:

 const [data, setData] = useState([ {name:'a'}, {name:'b'}, {name:'c'}]) 

And i also have an array of 3 random names:

const randomArray = ['d', 'e', 'f']

I wanna make a method that will take as an argument the randomArray and will update the new state like this:

data = [ {name:'d'}, {name:'e'}, {name:'f'}]

Any ideas?

3 Answers

You can use the map function. It returns a new array from the callback function. You can return the name property like so;

import { useEffect, useState } from "react";

export default function App() {
  const [data, setData] = useState([
    { name: "a" },
    { name: "b" },
    { name: "c" }
  ]);
  const randomArray = ["d", "e", "f"];

  const setNewValues = () => {
    setData(randomArray.map(name=> ({ name})));
  };

  useEffect(() => {
    console.log(data);
  }, [data]);
  return (
    <div className="App">
      <button onClick={setNewValues}>Set Data </button>
    </div>
  );
}

This is one way you can do it.

const ArrChange = () => {
 const randomArray = ['d', 'e', 'f'];
 const [data, setData] = useState([ {name:'a'}, {name:'b'}, {name:'c'}]) 
 const setData = () => {
   for(let i = 0; i < randomArray.lenght; i++)
      d[i].name = randomArray[i];
 }

 <Button onClick={setData}>
          Update
      </Button>
 }

Here you go! :)

const convertToJSON = array => {
  setData(array.map(name => ({ name })));
};
Related