0

enter image description here

I have request that response with this object and I need to display it, but I don't how to deal with because the ( 61, 70, 81 and so on)

here is my code which is not working

{ events.events.map(event =>(
    <div key={event.ID}> 
     <p>{event.name} </p>
    </div>))
}
4
  • 1
    events is object not array, so you can't use Array.map() method. Commented Jun 15, 2021 at 10:33
  • @RahulKumar is there a way that I can convert this object to array ? Commented Jun 15, 2021 at 10:35
  • You can only use map on arrays not on object. You either need to use Object.values, Object.entries or if you only want keys then Object.keys. Commented Jun 15, 2021 at 10:36
  • @MohamedAhmed added the answer below, can use Object.entries() method. Commented Jun 15, 2021 at 10:57

3 Answers 3

2

You are getting it as an object. So you can't use Array.map(). Instead you can use something like below

{ Object.values(events.events).map(event =>(
    <div key={event.ID}> 
     <p>{event.name} </p>
    </div>))
}

Object.values(yourObject) gets you the values of all the keys in yourObject as an array.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use Object.entries() which will return array of [key, value] pairs.

Alternatively you can also use other methods like Object.keys() and Object.values(). In below example I've used Object.entries() method.

const events = {
  "events": {
    "61": {
      "ID": "61",
      "NAME": "test_name_61",
      "EVENT_DATE": "30.06.2021 12:03:00",
      "MIN_PRICE": 1000
    },
    "70": {
      "ID": "70",
      "NAME": "test_name_70",
      "EVENT_DATE": "30.06.2021 12:03:00",
      "MIN_PRICE": 1100
    },
    "81": {
      "ID": "81",
      "NAME": "test_name_81",
      "EVENT_DATE": "30.06.2021 12:03:00",
      "MIN_PRICE": 2000
    }
  }
};

Object.entries(events.events).map(([key, event]) => {
  console.log(event);
});

React.js code:

{ Object.entries(events.events).map(([key, event]) => (
    <div key={event.ID}> 
     <p>{event.NAME} </p>
    </div>))
  ));
}

Comments

0

you can try

Object.values(events).map((eventValue) => console.log(eventValue))

to get values

Object.keys(events).map((key) => console.log(key))

to get key

Object.entries(events).map((event) => console.log(event))

to get event as array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.