user1941537
user1941537

Reputation: 6675

Map showing the keys, not only the values

If I have this object:

const json = {
  products: [
    {
      id: 0,
      name: "Chair Roby",
      style: "Leather",
      color: "red",
    }
  ]
};

I can map over the array inside of it and show all the items in the object inside the array like this:

const prod = json.products.map(item => {
  return (
      <ul>
        <li>
          {item.name}
        </li>
        <li>
          {item.style}
        </li>
         <li>
          {item.color}
        </li>
      </ul>
  );
});

This listed me the values, but how could I show also the keys such as name, style and color?

Upvotes: 0

Views: 45

Answers (4)

Markus
Markus

Reputation: 1636

const prod = json.products.map(item =>
      <ul>
          {Object.entries(item).map((key, value) =>
             <li>{key}: {value}</li>
          }
      </ul>
);

Upvotes: 1

rfschroeder
rfschroeder

Reputation: 410

The best aproach is this:

const prod = Object.keys(json.products).forEach(productKey => { return ( <ul> <li> {productKey} - {json.products[productKey]} </li> </ul> ); });

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370679

Use another nested map over the Object.entries of each item:

const json = {
  products: [
    {
      id: 0,
      name: "Chair Roby",
      style: "Leather",
      color: "red",
    },
    {
      foo: 'bar'
    }
  ]
};

class MyList extends React.Component {
  render() {
    return json.products.map((obj) => (
      <ul>
        { 
          Object.entries(obj).map(([key, val]) => (
            <li>
              {('key: ' + key +  ', val: ' + val)}
            </li>
          ))
        }
      </ul>
    ));
  }
}
ReactDOM.render(
  <MyList />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Upvotes: 2

Shravani
Shravani

Reputation: 1692

Try this

 Object.keys(json).map(Followed by necessary code)

Upvotes: 1

Related Questions