Home > database >  How to create array of objects through map?
How to create array of objects through map?

Time:04-29

I would like to have multiple arrays of objects like this.

E.g:

const pets = [
 {
  name: "cat",
  age: 4
 },
 {
  name: "dog",
  age: 6
 }
]

But I want to create it using a map. So I was trying something like this.

let pets = [];

pets.map((item) => {
 return (
  item.push({
      name: "cat",
      age: 4
   }, {
     name: "dog",
     age: 6
   })
 )
})

By this method, I'm getting an empty array.

So assuming this is incorrect, how would I go on and make this through a map.

Please any help would be appreciated.

CodePudding user response:

first of all map works by looping through an array but you have empty array let pets = []; so the loop doesn't even start ! that's why you are getting empty array

Secondly map essentially is a method through which we can create a new array with the help of an existing array so you have chosen a wrong way!

example of map

const fruits = ["Mango", "Apple", "Banana", "Pineapple", "Orange"];
console.log(fruits);

const uppercaseFruits = fruits.map((fruit)=>{
  return fruit.toUpperCase(); // this thing will be added to new array in every iteration
  });

console.log(uppercaseFruits);

but still ....

let pets = [""]; // an item so that loop can start

const myPets = pets.map((item) => {
 return (
  ([{
      name: "cat",
      age: 4
   },{
     name: "dog",
     age: 6
   }])
 )
})

console.log(myPets)

CodePudding user response:

//Usage of map: for example
let array = [1, 2, 3, 4, 5];

let newArray = array.map((item) => {
    return item * item;
})

console.log(newArray)  // [1, 4, 9, 16, 25]

map will not change the original array, if you don't assign a value to it, the original array will never be affected

And if you want to get what you want you use RANDOM like this

//random String
function randomString(e) {    
    e = e || 32;
    var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
    a = t.length,
    n = "";
    for (i = 0; i < e; i  ) n  = t.charAt(Math.floor(Math.random() * a));
    return n
}

//random Number
function GetRandomNum(Min,Max)
{
var Range = Max - Min;
var Rand = Math.random();
return(Min   Math.round(Rand * Range));
}
var num = GetRandomNum(10000,999999);
alert(num);

Then you can combine random strings and random numbers into a new Object through a function

  • Related