Ad

JavaScript Map Function With React.js Gives Me Index, But Not Value In The Index

- 1 answer

So I have something like this in my React file, which works fine:

 {this.props.profile.first_name}

The above code would output the actual value in there: "John Doe" for example.

But, when I try and loop through each one to check to see if some profiles are empty (if the user never inputted a first name for example), I can't get the actually content to display. I get undefined or indexes. So the below code doesnt' help me.

     var props = Object.keys(this.props.profile).map(function(key, index, value) {

        console.log(key);  ### gives me index
        console.log(index);  ### undefined
        console.log(key[value]);  ### gives me data, but a label name, not the  
                                  actually value
        console.log(index[value]); ##undefined

        if ([key[value]) {
            return (
                <li className="list-group-item">
                    <label>{key}</label>{[value]}
                </li>
            );
        }

    })

How do I grab the actual data value in there, so that like this"{this.props.profile.first_name} the key or value checks agains the actual content in there (i.e. "John Doe") and not just an index or undefined?

Ad

Answer

Object.keysreturns Array with Object keys, for example you have

this.props.profile = {
   first_name: 'name'
};

Object.keys(this.props.profile) returns ['first_name'], in order to get value in map you should do

Object.keys(this.props.profile).map(function (key) {
  console.log(this.props.profile[key]);
}, this);

Example

Ad
source: stackoverflow.com
Ad