Home > Net >  Iterating objects in React JS
Iterating objects in React JS

Time:10-27

What is the Error in the below code? I tried to iterate over the array of objects using the map. but I am receiving an error. Please find attached the code for reference.

import "./styles.css";

export default function App() {
const sample = [{
samplePath : "/website",
 par:{
  abc:"123",
  def: "678",
  ghi:"456"}
}];

const createURL = (re)=> {

const q = Object.entries(re.par)
    .map(([key, value]) => key  '=' value).join("&");

return "?"  q;
}

console.log(createURL(sample));

return (
  <div className="App">
    <h1>Hello CodeSandbox</h1>
    <h2>Start editing to see some magic happen!</h2>
  </div>
);
}

I am receiving the following error error

CodePudding user response:

You're trying to call Object.entries on re.par. In this case, re is an array, so calling .par on it returns undefined. I'm not sure what your desired result is, but if you access the first element in the array and then .par, maybe that's what you're after?

const sample = [{
samplePath : "/website",
 par:{
  abc:"123",
  def: "678",
  ghi:"456"}
}];

const createURL = (re)=> {

const q = Object.entries(re.par)
    .map(([key, value]) => key  '=' value).join("&");

return "?"  q;
}

console.log(createURL(sample[0]));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

In your example sample is an array, containing one object.

So, either, remove the [] such that sample is an object like you are referring to it in your code. Or, Object.entries(re[0].par)

  • Related