Burak ULU
Burak ULU

Reputation: 303

Using .map function for two dimensional array - React

I have a two dimensional array like this;

enter image description here

And I need to use a map function to display div elements as many as the length of the array.

I saved the state into localStorage to prevent the data from disappearing after refreshing the page.

const conditions = JSON.parse(localStorage.getItem("condition")).map((condition, index) => {
            return <div key={index} className="card bg-color-primary" style={{ height: "170px", width: "300px", borderColor: "#1E90FF", backgroundColor: "white", borderWidth: "2px" }}>
                    {_.isEmpty(this.state.rule.condition) ?
                        <div className="card-content" style={{ color: "black" }}>
                            <span className="card-title">New Condition</span>
                            <p>Click to edit</p>
                        </div> :
                        <div className="card-content" style={{ color: "black" }}>
                            <span className="card-title">{condition.property}</span>
                            <p>{condition.operator + " " + condition.value}</p>
                        </div>}
                    <div className="card-action">
                        <a href="javascript:;" style={{ color: "red" }}>OR</a>
                        <a href="javascript:;" style={{ color: "black" }}>AND</a>
                        <a onClick={this.handleOpen} style={{ color: "gray", cursor: "pointer" }}>EDIT</a>
                    </div>
                </div>
        });

After this scope of code, it throws an error like;

Uncaught TypeError: localStorage.getItem(...).map is not a function

NOTE: I already have JSON.parse but forgot to add it here so it is not the actual problem. My bad.

Upvotes: 3

Views: 9717

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104529

Data that you stored in localStorage is not a 2D array, it's an object having keys name, operator, property, value. To use map, data should be an array. Specify on which (field) array you want to run the map.

Also important part is, localStorage will return the stringified value, so you need to parse the it first.

Example- running map of name value:

JSON.parse(localStorage.getItem("condition")).name.map(.....)

Or if you want to run map on object then first use Object.keys() (return an array of all the keys) or Object.values (return array of all the values) to get the array first then run map on that.

Check this snippet:

let obj = {
   a: [1,2,3],
   b: [4,5,6]
}

Object.keys(obj).map(el => {
   console.log('key', el);
   obj[el].map(sub_el => console.log(sub_el));
})

Upvotes: 5

Related Questions