Rifat
Rifat

Reputation: 1888

javascript array of objects with most basic form

Need to store and access values on an array in react. So far I found solutions that uses filters or does not fit my requirements.

Just need to push a string value with string key, and retrieve it with same key. How to do it?

Code:

import "./styles.css";
import { useRef } from "react";

export default function App() {
  const Presence = useRef({});

  function objTest() {
    Presence.current.length = 0;
    const uid = "UID1"; //Date.now().toString();

    //let obj = { [uid]:{ presence: "Busy"} };
    let obj = { [uid]: "Busy" };

    Presence.current.push(obj);

    console.log(Presence.current, " , ", Presence.current[uid]);
  }

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>

      {objTest()}
    </div>
  );
}

Upvotes: 0

Views: 47

Answers (2)

Someone Special
Someone Special

Reputation: 13588

Why not use state?

const Component = () => {

 const [ state, setState ] = useState({});
 const [ arrayState, setArrayState ] = useState([])
 const [ savedUid, setSavedUid ] = useState('') //need to save your UID too

 function objTest() {
    
        const uid = "UID1"; //Date.now().toString();
        setState({ [uid]: 'Busy'}) // object
        setArrayState(prev => [...prev, { [uid]: 'Busy' }] ) //array of objects
        setSavedUid(uid) //save your uid
 }
 console.log('Object', state[savedUid])
 console.log('Array of Objects', arrayState[0][savedUid])

 return <button onClick={objTest}>Click Me</button>

}

Upvotes: 1

T J
T J

Reputation: 43156

Just need to push a string value with string key, and retrieve it with same key

All modern browsers support map, which does exactly what you want:

const Presence = useRef(new Map());

You can use it like:

Presence.current.set(key, value)
Presence.current.has(key)
Presence.current.get(key)

Old way would be use an object literal like you have const Presence = useRef({}); and do use Property_accessors#bracket_notation like Presence.current[uid] = "Busy" to add dynamic keys. Object literals don't have a length or size property and are harder to enumerate so I don't recommend it unless you need to support IE

Upvotes: 1

Related Questions