1

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 3

1

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>
  );
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot :) If my initial state instead of one attribute per json [{ name: 'a' }, etc.] , had two attributes for each json (e.g [{name:'a', number:4}, {name:'b', number:3}, {name:'c', number:2}] ), what would be the solution then? The final state I would like to have in this example is this: data = [ {name:'d' , number:4 } , {name:'e', number:3} , {name:'f', number:2} ]
you would then fully declare the callback function from map like so; setData(randomArray.map((item,index)=> { return { name:item.name, number:item.number } }));
0

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>
 }

2 Comments

You are re-defining the function returned by the hook. Don't do that.
@Janez please correct my code appreciated (y)
0

Here you go! :)

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

1 Comment

Code without an explanation is rarely useful, however. At least provide a sentence or two to explain what’s going on. Answering Technical Questions Helpfully

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.