2

Can someone help me with this, I am trying to achieve an object like so:

{ "docs": [
{ "_id": "item" },
{ "_id": "item" },
{ "_id": "item" }
] }

So I begin with having an object with a key docs which is an array I will push into

let query = { docs: [] };

i then have list of key value pair items like so, around 80:

{ _id: item }

which i push into docs in a forEach loop

 query.docs.push(item);

So when I go and stringify

JSON.stringify(query);

it returns the object but the array is empty.

{ "docs": [] }

I’ve no idea why this is happening. Anyone know an approach to go around this to achieve the desired result? Thanks in advance

Actual code:

let elasticQuery = {
    docs: []
  };

  axios({
    method: "post",
    headers: {
      "Content-Type": "application/json"
    },
    url: sent2VecUrl,
    data: {
      selected_text: query
    }
  }).then(results => {
    results.data.response.forEach(item => {
      elasticQuery.docs.push({ _id: item });
    });
  });


  console.log("without: " + elasticQuery + " with stringify :" + JSON.stringify(elasticQuery));

This is the server response:

enter image description here

3
  • 1
    This looks ok, can you show us the actual code though? Commented Aug 16, 2018 at 12:08
  • What's in the response? Commented Aug 16, 2018 at 12:11
  • 3
    The problem is that JSON.stringify(elasticQuery) is executed before results.data.response.forEach......, before you push values into the elasticQuery.docs array. Commented Aug 16, 2018 at 12:12

3 Answers 3

3

Move your console in .then function. This is asyn call and your console is printing before your promise is getting resolved.

axios({
method: "post",
headers: {
  "Content-Type": "application/json"
},
url: sent2VecUrl,
data: {
  selected_text: query
}})
.then(results => {
   results.data.response.forEach(item => {
      elasticQuery.docs.push({ _id: item });
   });
   console.log("without: " + elasticQuery + " with stringify :" + JSON.stringify(elasticQuery));
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, i moved the console.log to that position and it indeed showed changes, i completely missed the async aspect.
There was a guy who posted the answer but then deleted it before i could accept :( anyway i think it works now
0

You code looks fine.

.then(results => {
    results.data.response.forEach(item => {
      elasticQuery.docs.push({ _id: item });
    });

      console.log(elasticQuery); 
  });

Comments

0

instead of this:

results.data.response.forEach(item => {
      elasticQuery.docs.push({ _id: item });
});

do this:

  elasticQuery.docs = results.data.response.map(item => ({ _id: item }) )

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.