Home > Back-end >  Right way to iterate nested object
Right way to iterate nested object

Time:02-05

Hi all I have following code

I am using ReactJS.

I am trying to filter from my zipCode file that zip code object which one user will provide in input. That filtering logic was working good, but I can't to save my object in variable becouse I am doing something wrong.

I looked at this article but it didn't help me.

In this case I can see object when doing console log.

       Object.values(zipWithLocation).forEach((o) => {
        Object.values(o).forEach((second) => console.log("second", second));
       });

But I need to implement it in this way

      const first = Object.values(zipWithLocation).forEach((o) => {
         Object.values(o).forEach((a) => {
          return a;
        });
      });

     console.log("first", first);

But in this way it console log undefined.

Please help me fix the last example. It would help me to implement the following.

    return(
       <>
        <p>
         city -{first.City}, location: {first.State}
        <p>
        <p>{first.Delivery}</p>
        <p>please provide address: {first.Address} </p>
      </>
    )

CodePudding user response:

Since zipCodefromInput should be a key of zipCode, you can get a reference to the data by zipCode[zipCodefromInput] (no looping needed).

Try

import { useState } from "react";
import "./styles.css";
import zipCode from "./zipCodes";

export default function App() {
  const [zipCodefromInput, setZipCodeFromInput] = useState();

  if (zipCodefromInput in zipCode) {
    let first = zipCode[zipCodefromInput][0];
    console.log(first.City);
  } else {
    console.log("entered zip code not found in list");
  }

  return (
    <div className="App">
      <input
        placeholder="2101"
        onChange={(e) => {
          setZipCodeFromInput( e.target.value);
        }}
      />
    </div>
  );
}

CodePudding user response:

.forEach() does not return anything (hence undefined), you probably want to look at using .map() if you want to assign the array to a variable.

For your case it seems like .find() would best fit your needs since it traverses the array and stops at the first matching condition.

const array = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];

const firstB = array.find((item, index) => {
  console.log('item:', item, 'index:', index)
  return item === 'b'
});
console.log('firstB', firstB);

const forEachResult = array.forEach((item) => { return item; });
console.log('forEachResult', forEachResult);

const mapResult = array.map((item) => {return item});
console.log('mapResult', mapResult);

  •  Tags:  
  • Related