I am trying to create an array from another array
let a = ["a", "b", "c", ...]
let b = ["22", "33", "44"]
let desireResult = [
{
"name": "a",
"age": "22"
},
{
"name": "a",
"age": "33"
},
{
"name": "a",
"age": "44"
},
{
"name": "b",
"age": "22"
},
{
"name": "b",
"age": "33"
},
{
"name": "b",
"age": "44"
},
{
"name": "c",
"age": "22"
},
{
"name": "b",
"age": "33"
},
{
"name": "b",
"age": "44"
},
...
]
this is my code:
let profiles = a.map(name=>{
b.map(age=>{
return ({"name": name, "age":age})
})
})
Promise.all([profiles])
but map() has synchronous functionality. so one way is to use Promise.all([]) . but what about map() inside a map()?
4 Answers 4
You can do this by using flatMap and map and Here is the working example:
UPDATE:
let a = ["a", "b", "c",];
let b = ["22", "33", "44"];
var result = a.flatMap(name=>b.map(age=>({name, age})));
console.log(result);
Comments
I don't know where is the asynchronous part.
It's basically the same code you have but you don't return anything on the first map. I just added a return keyword. I also added flat() to convert array of array of objects to a single array of objects.
But you can do it with this code:
let a = ["a", "b", "c"]
let b = ["22", "33", "44"]
let profiles = a.map(name=>{
return b.map(age=>{
return ({"name": name, "age":age})
})
}).flat()
console.log(profiles)
1 Comment
You don't need Promise.all as there are no asynchronous stuff going on, what you need is a Cartesian product of the two arrays, which can be achieved by using a reduce/forEach combo like so:
let profiles = a.reduce((acc, name) => {
b.forEach(age => acc.push({ name, age }));
return acc;
}, []);
Demo:
let a = ["a", "b", "c"];
let b = [22, 33, 44];
let profiles = a.reduce((acc, name) => {
b.forEach(age => acc.push({ name, age }));
return acc;
}, []);
console.log(profiles);
Comments
let a = ["a", "b", "c"];
let b = ["22", "33", "44"];
Promise.all(a.map((key,index)=>({name: key,age: b[index]})))
.then(r=>console.log(r));
Another example :
let a = ["a", "b", "c"];
let b = ["22", "33", "44"];
const myPromise = wait => new Promise(resolve=>setTimeout(()=>resolve(Date.now()),wait));
Promise.all(a.map(async (key,index)=>({name: key,age: b[index], time: await myPromise(Math.floor(Math.random() * 1000) + 1)})))
.then(r=>console.log(r));
Promise.all([])" - This won't change anything. Especially not without a.then(). But this won't do anything useful either when there's nothing to wait for...