簡體   English   中英

將 object 的嵌套數組轉換為簡單的 Json object javascript

[英]convert nested array of object to simple Json object javascript

您好需要一些關於標准化對象數組的幫助。 我有這個嵌套數組,它有一些 json 對象,這些對象有數組。

  [
   {
    customerId: 20
    customerName: "customer 1"
    orderItems: [
       {
        productId: '23'
        productName: 'ice cream'
        price: '200'
        },
      ....
     ] 
   },
    customerId: 21
    customerName: "customer 2"
    orderItems: [
       {
        productId: '47'
        productName: 'bottle'
        price: '60'
        },
       {
        productId: '48'
        productName: 'shake'
        price: '544'
        },
       ....
     ] 
   },
 ]

我想要這樣

    [
     {
        customerId: 20
        customerName: "customer 1",
        productId: '23'
        productName: 'ice creems'
        price: '200',
        ....
     },
      {
        customerId: 21
        customerName: "customer 2",
        productId: '47'
        productName: 'bottle'
        price: '60',
        ....
      },
       {
        customerId: 21
        customerName: "customer 2",
        productId: '48'
        productName: 'shake'
        price: '544',
        ....
       }
     ]

有人可以在這方面幫助我嗎? 我已經嘗試過 map 運算符,但我無法遍歷內部數組。 謝謝

您可以采用Array#flatMap方法並采用非規范化數據。

 var data = [{ customerId: 20, customerName: "customer 1", orderItems: [{ productId: '23', productName: 'ice cream', price: '200' }] }, { customerId: 21, customerName: "customer 2", orderItems: [{ productId: '47', productName: 'bottle', price: '60' }, { productId: '48', productName: 'shake', price: '544' }] }], denormalized = data.flatMap(({ orderItems, ...customer }) => orderItems.map(order => ({...customer, ...order }))); console.log(denormalized);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

您可以使用.map().flat()方法獲得所需的 output:

 const data = [{ customerId: 20, customerName: "customer 1", orderItems: [{ productId: '23', productName: 'ice cream', price: '200' }] }, { customerId: 21, customerName: "customer 2", orderItems: [{ productId: '47', productName: 'bottle', price: '60' }, { productId: '48', productName: 'shake', price: '544' }] }]; const result = data.map( ({orderItems, ...rest}) => orderItems.map(o => Object.assign({}, rest, o)) ).flat(); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM