Home > Back-end >  React: How to iterate through dictionary
React: How to iterate through dictionary

Time:07-21

Learning React and I was wondering how could I iterate through a dictionary. I come from python and theres a .items() method that can return key and value...is there a similar function in React? I want to set the values into a const and store them for future use. Heres what I have so far. (The reason I need this is because my JSON response gives an array which I already iterated through, but then a dictionary which I need to of course pull values from). Thanks so much for your time. Any response helps :)

JSX:

function Home(){
  
  const [data, setData] = useState();
  const getData= ()=>{
    fetch('http://localhost:8070/api')
    .then(function(response){
      return response.json();
    })
    .then(function(myJson){
      console.log(myJson);
      setData(myJson)
    })
  }
  useEffect(()=>{
    getData()
  },[])


  return (
    <div className="Home">
      {
        data?.results.map(result =>(
            <p  style={{width: "8rem"}}>{JSON.stringify(result.items)}</p> // HERES THE DICTIONARY
        ))
      }
    </div>
    )
  
}

CodePudding user response:

You can use Map collection:

new Map(fooArr.map(i => [i.name, i.surname]));

As mdn says about Map collection:

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

An example:

let fooArr = [
  { name: 'name 1', surname: 'surname 1' },
  { name: 'name 2', surname: 'surname 2' }
];

let result = new Map(fooArr.map(i => [i.name, i.surname]));
console.log(JSON.stringify([...result])); 

As an alternative, you can use Set or just create simple object. Object has key-value too. Let me show an example:

let fooArr = [
  { name: 'foo', surname: 'bar' },
  { name: 'hello', surname: 'world' }
];


let object = fooArr.reduce(
  (obj, item) => Object.assign(obj, { [item.name]: item.surname }), {});

console.log(object)

CodePudding user response:

To add to the previous answer. This React guide explains the arrays and how to use or set your keys for them: https://reactjs.org/docs/lists-and-keys.html#keys I would recommend making <div>s for each result or make a <table> with <tr> and <td> to store the individual items. Give each div or row a key and it is a lot easier to use it afterwards.

CodePudding user response:

You can use Object.entries which is similar to python .items:

const data = {a: 1, b: 2}

console.log(Object.entries(data))

CodePudding user response:

When dealing with objects you can use Object.keys(), Object.values() and Object.entries(), which do a similar thing than their similarly named python counterparts. (keys(), values(), pairs())

const obj = { person: 'John' }
console.log(Object.entries(obj)) // ['person', 'John']

Some differences from python...

  • Differently from python, those functions return Arrays.

  • (python returns an iterable, which is not a list, and you may need to cast it to list() for indexed access).

Arrays are iterables (as lists are on Python), so you can write:

// loop over iterable syntax, similar to python's for in
for (const [k, v] of Object.entries(obj)) {

}

Extra info on objects:

  • On JS almost everything is an Object, so there is no difference on writing obj.property or obj['property']. On Python class instances and dictionaries require a bit different handling.

  • JS Object keys can only be strings. If you pass a non string to an object key, it will be cast to a string;

  • JS also has its Map and Set collections. Those classes have iterators of their own (instead of using Object.X, they have their own .entries() etc); You usually won't need to use Map and Set as JS Objects already cover most of the needs;

  • Related