![](/img/trans.png)
[英]How to Convert nested json to array of object in 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.