i have an array of objects in
[
{
"country": "USA",
"payment": [
{
"paymentType": "Visa",
"count": 1000
},
{
"paymentType": "MasterCard",
"count": 1000
}
]
},
{
"country": "CANADA",
"payment": [
{
"paymentType": "Visa",
"count": 1000
},
{
"paymentType": "MasterCard",
"count": 1000
}
]
},
{...}
]
I want to transform it into
[
["USA" , "VISA" , 10000 ],
["USA","Mastercard",1000],
[countryName2, paymentType,count] , ...
]
Can someone help me>?
I tried doing:
const data2 = data.map(function(elem) {
return [
elem.country,
elem.payment.map(b=> b.paymentType),
elem.payment.map(c=>c.count),
]
})
but the output i get is not what i want, if someone could show how to do it,
You can do this with a nested map where each array entry is created by extracting data from payment
prefixed with the outer country
.
const data = [{"country":"USA","payment":[{"paymentType":"Visa","count":1000},{"paymentType":"MasterCard","count":1000}]},{"country":"CANADA","payment":[{"paymentType":"Visa","count":1000},{"paymentType":"MasterCard","count":1000}]}]; const data2 = data.flatMap(({ country, payment }) => payment.map(({ paymentType, count }) => [ country, paymentType, count ]) ); console.log(data2);
.as-console-wrapper { max-height: 100%;important; }
The flatMap()
on the outer map removes the extra level of nesting created in the result.
You can use flat Array function. Here:
const data2 = data
.map(state => state.payment.map(statePayment => [state.country, statePayment.paymentType, statePayment.count]))
.flat();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.