I am seeking the most efficient method to solve this problem by utilizing JavaScript's native array methods (map, reduce, etc.).
If given an array of n objects, my goal is to create another array that contains m objects for each element in the original array. Although I can achieve this using traditional "for" loops to iterate through the array, I am curious if there is a solution using the native array methods.
For example:
Suppose I have an array with n elements like "ObjectA":
var objectA = {
name: "xxx",
tels: ["yyy","zzz"]
};
I aim to generate another array of objects of type "ObjectB":
var objectB = {
name: "xxx",
tel: "yyy"
};
Thus, if the initial array only contained objectA, the desired outcome would be:
[
{
name: "xxx",
tel: "yyy"
},
{
name: "xxx",
tel: "zzz"
}
]
I attempted using two nested "map" calls, but encountered limitations as the callback function can only return one element at a time.
var array1 = [objectA];
var array2 = array1.map(function(objectA){
return objectA.tels.map(function(tel){
return {
name : objectA.name,
tel : tel
};
});
});
Returning another array within the callback resulted in an array of arrays, which is not the intended outcome. The result of Array2 was:
[
[
{
name: "xxx",
tel: "yyy"
},
{
name: "xxx",
tel: "zzz"
}
]
]
Should I resort to using traditional for loops, or is there a native JavaScript approach available?