简体   繁体   English

将 object 的嵌套数组转换为简单的 Json object javascript

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

hi need some help regarding normalizing array of objects.您好需要一些关于标准化对象数组的帮助。 i have this nested array which has some json objects and those objects have array.我有这个嵌套数组,它有一些 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'
        },
       ....
     ] 
   },
 ]

i want it like this我想要这样

    [
     {
        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',
        ....
       }
     ]

Can someone help me in this regard?有人可以在这方面帮助我吗? i have tried map operator but i couldn't loop through inner array.我已经尝试过 map 运算符,但我无法遍历内部数组。 thanks谢谢

You could take a Array#flatMap approach and take the denormalized data.您可以采用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; }

You can use .map() and .flat() methods to get the desired output:您可以使用.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