如何使对象的嵌套阵列变平并复制父

发布于 2025-01-22 07:49:19 字数 1399 浏览 4 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

迟月 2025-01-29 07:49:19

您可以使用array.flatmap()迭代对象,然后使用属性使用array.map() ,然后与其余对象。 array.flatmap()还将将数组的数组变为一个数组。

const fn = arr => arr.flatMap(({ attributes, ...rest }) => 
  attributes.map(o => ({
    ...rest,
    ...o
  }))
)

const products = [{"productId":"1","attributes":[{"variant":"red","price":"134.00"}]},{"productId":"2","attributes":[{"variant":"green","value":"3400.00"},{"variant":"pink","price":"342.00"}]}]

const result = fn(products)

console.log(result)

使用RAMDA,您可以使用r.chain迭代和平坦数组。要获得一系列属性与父母相结合,您可以将r.ap作为两个函数组合器:

  1. 提取属性数组,然后将其应用于第二个功能。
  2. 获取其余对象(无属性),并创建将其合并到迭代对象的映射函数。
const { chain, ap, pipe, prop, applyTo, omit, mergeRight, map } = R

const fn = chain(ap(
  pipe(prop('attributes'), applyTo),
  pipe(omit(['attributes']), mergeRight, map)
))

const products = [{"productId":"1","attributes":[{"variant":"red","price":"134.00"}]},{"productId":"2","attributes":[{"variant":"green","value":"3400.00"},{"variant":"pink","price":"342.00"}]}]

const result = fn(products)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

You can use Array.flatMap() to iterate the objects, and then iterate the attributes with Array.map(), and combine with the rest of the object. The Array.flatMap() would also flatten the array of arrays to a single array.

const fn = arr => arr.flatMap(({ attributes, ...rest }) => 
  attributes.map(o => ({
    ...rest,
    ...o
  }))
)

const products = [{"productId":"1","attributes":[{"variant":"red","price":"134.00"}]},{"productId":"2","attributes":[{"variant":"green","value":"3400.00"},{"variant":"pink","price":"342.00"}]}]

const result = fn(products)

console.log(result)

With Ramda, you can iterate and flatten the array using R.chain. To get an array of attributes combined with their parents, you can use the R.ap as combinator of two functions:

  1. Extracts the attributes array, and then applies it to the 2nd function.
  2. Gets the rest of the object (without the attributes), and creates a mapping function that merges it to the iterated objects.

const { chain, ap, pipe, prop, applyTo, omit, mergeRight, map } = R

const fn = chain(ap(
  pipe(prop('attributes'), applyTo),
  pipe(omit(['attributes']), mergeRight, map)
))

const products = [{"productId":"1","attributes":[{"variant":"red","price":"134.00"}]},{"productId":"2","attributes":[{"variant":"green","value":"3400.00"},{"variant":"pink","price":"342.00"}]}]

const result = fn(products)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

清引 2025-01-29 07:49:19

您可以使用 /code> and 数组#flat 如下:

const products = [ { "productId": "1", "attributes": [ { "variant":"red", "price": "134.00" } ] }, { "productId": "2", "attributes": [ { "variant": "green", "value": "3400.00" }, { "variant": "pink", "price": "342.00" } ] } ];

const output = products.map(({productId,attributes}) => 
    attributes.map(({variant,price}) => ({productId,variant,price}))
)
.flat();

console.log( output );

或仅名称属性,如果还有其他属性:

const products = [ { "productId": "1", "attributes": [ { "variant":"red", "price": "134.00" } ] }, { "productId": "2", "attributes": [ { "variant": "green", "value": "3400.00" }, { "variant": "pink", "price": "342.00" } ] } ];

const output = products.map(({attributes,...rest}) => 
    attributes.map(attribute => ({...rest,...attribute}))
)
.flat();

console.log( output );

You can use Array#map and Array#flat as follows:

const products = [ { "productId": "1", "attributes": [ { "variant":"red", "price": "134.00" } ] }, { "productId": "2", "attributes": [ { "variant": "green", "value": "3400.00" }, { "variant": "pink", "price": "342.00" } ] } ];

const output = products.map(({productId,attributes}) => 
    attributes.map(({variant,price}) => ({productId,variant,price}))
)
.flat();

console.log( output );

Or to only name attributes, in case there are other properties:

const products = [ { "productId": "1", "attributes": [ { "variant":"red", "price": "134.00" } ] }, { "productId": "2", "attributes": [ { "variant": "green", "value": "3400.00" }, { "variant": "pink", "price": "342.00" } ] } ];

const output = products.map(({attributes,...rest}) => 
    attributes.map(attribute => ({...rest,...attribute}))
)
.flat();

console.log( output );

夜空下最亮的亮点 2025-01-29 07:49:19

此代码应该对您有用:

const transformedProducts = [];

products.forEach((product) => {
    product.attributes.forEach((attribute) => {
        transformedProducts.push({
            productId: product.productId,
            ...attribute,
        });
    });
});

This code should work for you:

const transformedProducts = [];

products.forEach((product) => {
    product.attributes.forEach((attribute) => {
        transformedProducts.push({
            productId: product.productId,
            ...attribute,
        });
    });
});
記柔刀 2025-01-29 07:49:19

在我的情况下,我的数组是在对象中有对象,那里有子阵列。我想要一个带有所有子对象的单个数组,

因此我使用此功能将所有对象在单个数组中获取

  let array = [
      {
        id: 1,
        title: 't1',
        sort_order: 200,
        childs: [
          {
            id: 2,
            title: 't2',
            sort_order: 200,
            childs: [],
          },
          {
            id: 3,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
          {
            id: 4,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
          {
            id: 5,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
          {
            id: 6,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
        ],
      },
      {
        id: 7,
        title: 'راهنما',
        sort_order: 'mytitle',
        childs: [
          {
            id: 8,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
          {
            id: 9,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
          {
            id: 10,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
        ],
      },
    ];

这是我的代码

let flattenArray = [];

function flatten(a) {
  flattenArray.push(a);
  if (a.childs?.length) a.childs.map(flatten);
}

array?.map((el) => {
  flattenArray.push(el);
  if (el.childs?.length) el.childs.map(flatten);
});

console.log(flattenArray);

结果:

[
    {
        "id": 1,
        "title": "t1",
        "sort_order": 200,
        "childs": [
            {
                "id": 2,
                "title": "t2",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 3,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 4,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 5,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 6,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            }
        ]
    },
    {
        "id": 2,
        "title": "t2",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 3,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 4,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 5,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 6,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 7,
        "title": "راهنما",
        "sort_order": "mytitle",
        "childs": [
            {
                "id": 8,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 9,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 10,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            }
        ]
    },
    {
        "id": 8,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 9,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 10,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    }
]

In my case my array is having objects with in objects there are child array. I wanted a single array with all child objects

So I used this function to get all objects in a single array

  let array = [
      {
        id: 1,
        title: 't1',
        sort_order: 200,
        childs: [
          {
            id: 2,
            title: 't2',
            sort_order: 200,
            childs: [],
          },
          {
            id: 3,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
          {
            id: 4,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
          {
            id: 5,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
          {
            id: 6,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
        ],
      },
      {
        id: 7,
        title: 'راهنما',
        sort_order: 'mytitle',
        childs: [
          {
            id: 8,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
          {
            id: 9,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
          {
            id: 10,
            title: 'mytitle',
            sort_order: 200,
            childs: [],
          },
        ],
      },
    ];

here is my code

let flattenArray = [];

function flatten(a) {
  flattenArray.push(a);
  if (a.childs?.length) a.childs.map(flatten);
}

array?.map((el) => {
  flattenArray.push(el);
  if (el.childs?.length) el.childs.map(flatten);
});

console.log(flattenArray);

results :

[
    {
        "id": 1,
        "title": "t1",
        "sort_order": 200,
        "childs": [
            {
                "id": 2,
                "title": "t2",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 3,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 4,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 5,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 6,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            }
        ]
    },
    {
        "id": 2,
        "title": "t2",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 3,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 4,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 5,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 6,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 7,
        "title": "راهنما",
        "sort_order": "mytitle",
        "childs": [
            {
                "id": 8,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 9,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            },
            {
                "id": 10,
                "title": "mytitle",
                "sort_order": 200,
                "childs": []
            }
        ]
    },
    {
        "id": 8,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 9,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    },
    {
        "id": 10,
        "title": "mytitle",
        "sort_order": 200,
        "childs": []
    }
]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文