0

I am new into Javascript and actually I'm facing following problem. I get JSON-object by calling an API. I get more than one object, that is fine. The objects are like this:

{"version": 1.0.1,
 "id": 125,
 "name": "Elmos App Test",
 "creationDate": "2017-05-28",
},
{"version": 1.0.4,
 "id": 25,
 "name": "Elmos App Prod",
 "creationDate": "2017-05-25",
},
{"version": 1.1,
 "id": 14,
 "name": "Elmos App Int",
 "creationDate": "2017-04-23",
}

I hope it is not too difficult to identify the JSON here. MY problem is now to save the three names in one variable.

Response of call should be like --> "Your apps are Elmos App Test Elmos App Prod Elmos App Int"

I actually have following Javascriptcode:

function getJSON(callback){
        request.get(url(), function(error, response, body){
            var d = JSON.parse(body);
            var result = d.name;//query for result
            if (result > null){
                callback(result);}
            else
         {
            callback("ERROR");
         }
    });

As you can see i try to save the name into the var result. Hope someone can help me out there. Thank you.

6
  • 3
    I hope your first code block has [ ] around it. Commented Jun 13, 2017 at 13:36
  • So loop over them and concatenate a string. Commented Jun 13, 2017 at 13:37
  • 2
    If that's the complete response then it's not valid JSON. Commented Jun 13, 2017 at 13:37
  • 1
    result > null, huh? Commented Jun 13, 2017 at 13:39
  • 1
    also need to quote the float numbers so your response should look like: [{"version": "1.0.1", "id": 125, "name": "Elmos App Test", "creationDate": "2017-05-28",},{"version": "1.0.4", "id": 25, "name": "Elmos App Prod", "creationDate": "2017-05-25",},{"version": "1.1", "id": 14, "name": "Elmos App Int", "creationDate": "2017-04-23"}] Commented Jun 13, 2017 at 13:41

1 Answer 1

3

You can use Array#map() to only get the names and then join() to concatenate them

const array = [{"version": "1.0.1", "id": 125, "name": "Elmos App Test", "creationDate": "2017-05-28", }, {"version": "1.0.4", "id": 25, "name": "Elmos App Prod", "creationDate": "2017-05-25", }, {"version": "1.1", "id": 14, "name": "Elmos App Int", "creationDate": "2017-04-23" }],
  name = array.map(a=>a.name).join(' ');
console.log(name);

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

2 Comments

But obviously you stored the JSON in the array... how can i store the response in the array?
Don't you already have an array ? What kind of data do you get from request.get(url)?

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.