CodingisLife
CodingisLife

Reputation: 107

Mapping the object key and value to the component with different properties

myObj = {name: 'Alice', age: '19', weight: 52}

I wanted all the key and values inside the object to be rendered to one label and input respectively.

I have tried it using Object.entries but then key and values cannot be separated. Any suggestion for doing this? Thank you

Upvotes: 0

Views: 623

Answers (2)

devserkan
devserkan

Reputation: 17598

I don't know what kind of problem do you have with Object.entries but it can be used in your situation:

class App extends React.Component {
  state = {
      myObj: {
        name: 'Alice', age: '19', weight: 52
        },
  }

  render() {
    const { myObj } = this.state;
    return (
      <div>
      {
        Object.entries( myObj ).map( ( [ key, value ] ) =>
        <div key={key}>
          <label>{key}</label>
          <input placeholder={value} />
        </div>
        )
      }
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Upvotes: 3

Manoz
Manoz

Reputation: 6587

You can do it with Object.keys too. It will iterate through object keys

class App extends React.Component {
  state = {
      myObj: {
        name: 'Alice', age: '25', weight: 55
        },
  }

  render() {
    const { myObj } = this.state;
    return (
      <div>
      {
        Object.keys(myObj).map((key,index) =>
        <div key={index}>
          <label>{key}</label>
          <input placeholder={this.state.myObj[key]} />
        </div>
        )
      }
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Upvotes: 4

Related Questions