0

In my node app i pass bunch of queries as Object.I have to form as exact format of request.

Consider my request as:

{q0:{query0},q1:{query1},q2:{query1}}

My reponse should be {q0:{response0},q1{response1},q2{response2}

My actual query(In my app):

{"q0":{"query":"James Madison","type":"/people/presidents","type_strict":"should"},
"q1":{"query":"George Washington","type":"/people/presidents","type_strict":"should"},
"q2":{"query":"John Adams","type":"/people/presidents","type_strict":"should"},
"q3":{"query":"James Monroe","type":"/people/presidents","type_strict":"should"},
"q4":{"query":"Thomas Jefferson","type":"/people/presidents","type_strict":"should"}}

But my response is coming as:

{"result":[q0result,q1result,q3result]}

My code:

for (var id in presidents ) {
        var match
        if (query == presidents[id]) {
        //console.log(" Inside match")
            match = true;
        }
        else {
            match = false;
        }
        matches.push({
            "id": id,
            //"name": name,
            "score": 100,
            "match": match,
            "type": [{
                "id": "/people/presidents",
                "name": "US President"
            }]
        })
    }
     callback(matches);



json = JSON.stringify({"result":matches});
  res.writeHead(200, {'content-type':'application/json'});
  res.end(json);

Please help me to solve this..Thanks in advance.

1 Answer 1

1

You are pushing the result in an array instead you should create a property in the result object as below

var matches = {};
for (var id in presidents ) {

        if (query == presidents[id]) {
        //console.log(" Inside match")
            match = true;
        }
        else {
            match = false;
        }
        matches[id] ={
            "id": id,
            //"name": name,
            "score": 100,
            "match": match,
            "type": [{
                "id": "/people/presidents",
                "name": "US President"
            }]
        };
    }
     callback(matches);
Sign up to request clarification or add additional context in comments.

1 Comment

You have declare matches before for loop, see the edited answer

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.