I am very new to javascript, and so far everything was fine until I ran into this dilemma, I need to restructure a JSON file as follows:
{
firstName: "Joel",
lastName: "Munz",
total: 154,
transaction: "111111",
articles:[
{
sku: "abc123456",
number: 2,
price: 65
},
{
sku: "def123456",
number: 2,
price: 24
}
]
},
{
firstName: "Patel",
lastName: "Dass",
total: 85,
transaction: "222222",
articles: [
{
sku: "abc123456",
number: 1,
price: 65
},
{
sku: "def123456",
number: 2,
price: 10
}
]
}
And my source file has the following structure:
{
"transactions":[
{
"items":[
{
"price":65,
"sku":"abc123456"
},
{
"price":65,
"sku":"abc123456"
},
{
"price":12,
"sku":"def123456"
},
{
"price":12,
"sku":"def123456"
}
],
"total":154,
"transaction":"111111",
"customer":{
"firstName":"Joel",
"lastName":"Munz"
}
},
{
"items":[
{
"price":65,
"sku":"abc123456"
},
{
"price":10,
"sku":"ghi123456"
},
{
"price":10,
"sku":"ghi123456"
}
],
"total":85,
"transaction":"222222",
"customer":{
"firstName":"Patel",
"lastName":"Dass"
}
}
]
}
what I have tried is the following, but it doesn’t have the structure that I need. I’ve read about using the reduce () forEach () function, but I don’t know how to implement it to match the format I need.
const trans = data.transactions.map(transaction => ({
"firstName": transaction.customer.firstName,
"lastName": transaction.customer.lastName,
"total":transaction.total,
"order_id": transaction.transaction, //OP
"articles": {
"sku":transaction.items.map(Item => Item.sku),
"number":transaction.items.map(Item => Item.sku).length,
"price":transaction.items.map(Item => Item.price)}
}))
console.log(trans);
Any suggestions?
Thanks for the help!
You’re extremely close, it’s just that instead of mapping each property of the
articles
property, you want to map the entiretransaction.items
array and assign the returned array toarticles
.instead of: