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

时间:2020-04-27 15:05:31

标签: javascript arrays reactjs

他需要一些有关标准化对象数组的帮助。 我有一个嵌套数组,其中包含一些json对象,而那些对象具有数组。

x = torch.max(x,torch.tensor([0.]))

我想要这样

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

有人可以在这方面帮助我吗?我已经尝试过地图运算符,但无法遍历内部数组。 谢谢

2 个答案:

答案 0 :(得分:1)

您可以采用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; }

答案 1 :(得分:1)

您可以使用.map().flat()方法来获得所需的输出:

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; }

相关问题