Here is picture of my data I have:
Im trying to get array of objects, which will look like this:
[{
length: 2,
item: {
imgSource: "/sushi/test2.png"
ingredients: "Nori, Cucumber, Rice, Cream cheese, Sesame, Unagi sauce"
name: "sushi1"
price: 133
weight: 120}
},
{
length: 1,
item: {
imgSource: "/sushi/test1.png"
ingredients: "Salmon, Nori, Cucumber, Rice, Cream cheese"
name: "sushi2"
price: 119
weight: 120}
}]
The best way i think of is to use reduce function, but i have no idea how to use it right, can anyone help me?
>Solution :
It’s pretty simple actually:
var items = [
[{
imgSource: "/sushi/test2.png",
ingredients: "Nori, Cucumber, Rice, Cream cheese, Sesame, Unagi sauce",
name: "sushi1",
price: 133,
weight: 120,
}, {
imgSource: "/sushi/test2.png",
ingredients: "Nori, Cucumber, Rice, Cream cheese, Sesame, Unagi sauce",
name: "sushi1",
price: 133,
weight: 120,
}],
[{
imgSource: "/sushi/test1.png",
ingredients: "Salmon, Nori, Cucumber, Rice, Cream cheese",
name: "sushi2",
price: 119,
weight: 120,
}]
]
items = items.reduce(function(carry, item) {
if (!carry.hasOwnProperty(item.name)) {
carry.push({
count: item.length,
item: item[0]
})
}
return carry;
}, [])
console.log(items)
