Reputation: 285
I want to know if there is it is possible to split up an object into multiple objects. I have an array of objects that has another array in it and I was wondering if it is possible to split those objects for each object in the inner array. Something like:
obj1 = [{
a: 1,
b: [{c: 2},{d: 3}],
e: 4
}]
to
obj2 =[
{
a: 1,
b: [{c: 2}],
e: 4
},
{
a: 1,
b: [{d: 3}],
e: 4
}
]
The object is always in this form, whether it has one object or hundreds. While some objects may have more fields in them, there is only one field with an array. Currently, I am mapping across the original array and then mapping again inside the b
array to get to each object in there. However, I do not know where to go from there as the return object from that map would just be the original array. I do not know how to split the b
array and map it with the original one. I thought of {...orig, b: map()} but I don't think it will work with every object
Upvotes: 2
Views: 2170
Reputation: 5283
You were on the right track according to the description in your post. You have to loop through your source object, and inside each iteration, loop through your b
array to extract each element and push it with the source iteration element in a new object into a target array.
var source = [{
a: 1,
b: [{ c: 2 }, { d: 3 }],
e: 4
}];
// define target as an array
var target = [];
// loop through source
source.forEach((srcElement) => {
// loop through `b` array attribute
srcElement.b.forEach((bElement) => {
// push object into target with source element attributes
// and current `b` element wrapped into an array
target.push({
...srcElement,
b: [bElement]
});
});
});
console.log(target);
NOTE: this solution assumes that on each iteration on your source object, the b
attribute exists and is of type Array
.
Upvotes: 2