JavaScript: How to construct an array of json objects using map

Sandhya Sadanandan
Aug 24, 2017 · 1 min read

What does map do ?

Answer: It creates a new array with the results of calling a function on every element in the calling array.

Example:

var numbers = [ 1, 2, 3, 4];var multiplesOfTen = numbers.map( function(num) {    return num * 10;
});
console.log(numbers); //prints [1, 2, 3, 4]
console.log(multiplesOfTen); //prints [10, 20, 30, 40]

How does JSON object look like?

Answer: JSON objects are written as key/ value pairs

Example:

var Person = { "name" : "Amy", "Age" : 15 }
console.log(Person.Age); //Prints 15

Let us solve a problem using map method. We have a JSON object say “orders” with lot of keys like name, description, date, status. We need an array of orders whose status is delivered. This array of orders will have information about order name and order description only.

Answer:

var orders = [ { "name" : "chain", "description" : "necklace chain", "status": "shipped"} , {"name": "pen", "description" : "ball pen", "status": "shipped"}, {"name": "book", "description" : "travel diary", "status": "delivered"},{"name": "brush", "description" : "paint brush", "status": "delivered"}];console.log(orders); 
var orderInfo = orders.map( function(order) {
if( order.status === "delivered"){
var info = { "orderName": order.name,
"orderDesc": order.description
}
return info;
}
});
console.log(orderInfo);

Reference:

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade