[英]How to split one object with an array in it to multiple objects
I want to know if there is it is possible to split up an object into multiple objects.我想知道是否可以将 object 拆分为多个对象。 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.
我有一个对象数组,其中包含另一个数组,我想知道是否可以为内部数组中的每个 object 拆分这些对象。 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. object始终是这种形式,不管是一个object还是几百个。 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.目前,我正在映射原始数组,然后在
b
数组中再次映射以到达其中的每个 object。 However, I do not know where to go from there as the return object from that map would just be the original array.但是,我不知道 go 从那里到哪里,因为从 map 返回的 object 将只是原始数组。 I do not know how to split the
b
array and map it with the original one.我不知道如何将
b
阵列和 map 与原始阵列分开。 I thought of {...orig, b: map()} but I don't think it will work with every object我想到了 {...orig, b: map()} 但我认为它不适用于每个 object
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.您必须遍历源 object,并在每次迭代中循环遍历
b
数组以提取每个元素,并将其与新 object 中的源迭代元素一起推送到目标数组中。
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
.注意:此解决方案假定在您的源 object 的每次迭代中,
b
属性存在并且是Array
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.