Home > Software design >  Error in displaying where there's an a array inside of the object
Error in displaying where there's an a array inside of the object

Time:03-12

this is what the data shows inside the console:

enter image description here

I tried displaying it with these but it failed

 {Object.entries(value).map(([key, value]) => {
        return (
          <p key={key}>
            <li>
              {key}
              {value}
              {console.log(value.id)} //this will show as undefined
            </li>
          </p>
        );
      })}

{value} will show this error :

Objects are not valid as a React child (found: object with keys {color, quantity}). If you meant to render a collection of children, use an array instead.

{value.id} or the {value.name} will show as undefined

With the map, it will say that value.map is not a function

 {value.map((value, key) => (
    <>
      <div>{value.id}</div>
      <div>{value.name}</div>
    </>
  ))}

codesandbox: https://codesandbox.io/s/display-the-manipulated-data-dy204r

CodePudding user response:

Your object has a complex structure, and in order to iterate, you need to check if one of the items is Array using Array.isArray(), if yes, then loop them and use, else use the properties directly


Below is the working code of the mock of your object and iteration. I have just logged the values, you can use them in any way you want

let myObj = {
  s: [{
    color: 'a',
    q: '8'
  }, {
    color: 'b',
    q: '2'
  }],
  name: 'Anne',
  id : 18
}

Object.keys(myObj).forEach(function(key) {
  if (Array.isArray(myObj[key])) {
    myObj[key].forEach(function (item, index) {
      console.log(item.color);
      console.log(item.q);
    });
  }
  else
    console.log(myObj[key])
});

CodePudding user response:

You can do something like this

{Object.entries(value).map((v, key) => {
    return (
      <p key={key}>
        <li>
          {key}
          {v.name}
          {console.log(v.id)} //this will show as undefined
        </li>
      </p>
    );
  })}
  • Related