Build an object from three lines of input, and print it in two ways.
What to build
A program that collects separate values into one object.
Requirements
- Read a name, an age and a city.
- Make an object with the properties
name,ageandcity, in that order. The age must be a number. - Print the object with
JSON.stringify. - Print
NAME lives in CITY, using the object's properties.
Input
Three lines.
Output
Two lines.
Constraints
The age is a whole number from 1 to 120.
Example
Input:
Mitu
21
Dhaka
Output:
{"name":"Mitu","age":21,"city":"Dhaka"}
Mitu lives in Dhaka
Why it works
Once the values are grouped, one name carries all of them. JSON shows the difference between types: the name is in quotes because it is a string, and the age is not, because it is a number.
Examples
Example 1 · Input
Mitu 21 Dhaka
Expected output
{"name":"Mitu","age":21,"city":"Dhaka"}
Mitu lives in Dhaka
Example 2 · Input
Rahim 30 Sylhet
Expected output
{"name":"Rahim","age":30,"city":"Sylhet"}
Rahim lives in Sylhet
Hints
Hint 1
An object literal can use your variables as values: { name: name, age: age }.
Hint 2
Convert the age to a number, so that it has no quotes in the JSON.
Hint 3
JSON.stringify(student) gives the text of the object.
Solution
Show one correct solution (try it yourself first)
const name = prompt();
const age = Number(prompt());
const city = prompt();
const student = { name: name, age: age, city: city };
console.log(JSON.stringify(student));
console.log(`${student.name} lives in ${student.city}`);