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

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

https://www.w3schools.com/js/js_json_objects.asp

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect