Denn
Denn

Reputation: 487

Loop through an elasticsearch object response in react

I am making an api request to elasticsearch which responses with an object.. something like this:

{
"body": {
    "took": 34,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2282,
            "relation": "eq"
        },
        "max_score": 1.6155963,
        "hits": [
            {
                "_index": "newspaper",
                "_type": "_doc",
                "_id": "aUU1IXUB9r40FEEAkQ8p",
                "_score": 1.6155963,
                "_source": {
                    "message": "message one",
                    "attachments": [],
                     .
                     .
                     .
                }
            },
            {
                "_index": "newspaper",
                "_type": "_doc",
                "_id": "aUU1IXUB9r40FEEAkQ8p",
                "_score": 1.6155963,
                "_source": {
                    "message": "message two",
                    "attachments": [],
                     .
                     .
                     .

Using hooks I have initialized const [results, setResults] = useState({}); and set the result after axios call just fine.

If I get the object keysas follows:

return (
  <div id="results" className="search-results">       
    
    {(Object.keys(results))}
  </div>
);

I get 5 keys ["body","statusCode","headers","warnings","meta"]

bodystatusCodeheaderswarningsmeta

How do I make a loop to get all the messages inside the _source of the hits array inside the body? would like to list them.

Upvotes: 1

Views: 165

Answers (1)

Vivek Sharma
Vivek Sharma

Reputation: 553

You can do something like this:

return (
    <div id="results" className="search-results">       

    {result && result.body.hits.hits.map(hit=>(
        <p>{hit['_source']['message']}</p>
    )}

    </div>
);

Upvotes: 1

Related Questions