I have the following object that holds workouts for specific days:
{
"2019-03-02": [
{
"id": 1,
"workout_day": "2019-03-02",
"title": "Swimming",
"description": "",
"completed": true,
"points": 5
},
{
"id": 2,
"workout_day": "2019-03-02",
"title": "Running",
"description": "",
"completed": false,
"points": 0
},
{
"id": 3,
"workout_day": "2019-03-02",
"title": "Rowing",
"description": "",
"completed": true,
"points": 3
},
],
"2019-03-05": [...]
}
I want to get a new object that shows for each day how many workouts exist, how much of them have been completed and a sum for the points, like so:
{
"2019-03-02": {
"workouts": 3,
"workouts_completed": 2,
"total_points": 8
},
"2019-03-05: {...}
}
However, I'm totally stuck at the moment. Thanks for help!
You've multiple solution to achieve this. Here is one that combined Object.entries + Array.reduce.
Object.entries(input).reduce((acc, [date, workouts]) => {
const completed = workouts.filter(workout => workout.completed);
return {
...acc,
[date]: {
workouts: workouts.length,
workouts_completed: completed.length,
total_points: completed.reduce((acc, workout) => acc + workout.points, 0),
}
};
}, {});
Note that Object.entries is not available in all the major browsers.
This will reduce your data into the one you want to transform to
const data = {
'2019-03-02': [{
id: 1,
workout_day: '2019-03-02',
title: 'Swimming',
description: '',
completed: true,
points: 5
},
{
id: 2,
workout_day: '2019-03-02',
title: 'Running',
description: '',
completed: false,
points: 0
},
{
id: 3,
workout_day: '2019-03-02',
title: 'Rowing',
description: '',
completed: true,
points: 3
}
],
'2019-03-03': [{
id: 1,
workout_day: '2019-03-02',
title: 'Swimming',
description: '',
completed: true,
points: 7
},
{
id: 2,
workout_day: '2019-03-02',
title: 'Running',
description: '',
completed: false,
points: 0
},
{
id: 3,
workout_day: '2019-03-02',
title: 'Rowing',
description: '',
completed: false,
points: 3
}
]
}
const reducedData = Object.keys(data).reduce((acc, key) => {
acc[key] = {
workouts: data[key].length,
workouts_completed: data[key].reduce((acc, item) => {
if (item.completed) return acc + 1
return acc
}, 0),
total_points: data[key].reduce((acc, item) => {
return acc + item.points
}, 0)
}
return acc
}, {})
console.log(reducedData)
Assuming you have your object that holds workouts for specific days in an object called json, you can use Object.keys() to iterate over all the keys. Then you can map over this and get the workouts for one specific day at a time. You can then use that to create an object for each day. To calculate stuff like totalPoints you'll use reduce to sum up the total points.
Object.keys(json).map(key => {
return {
[key]: {
workoutsCompleted: json[key].length,
totalPoints: json[key].reduce((accum, workout) => accum + workout.points, 0)
}
};
});
This does the job.
I used Array.prototype.reduce and destructuring with default values.
var data = {
"2019-03-02": [{
"id": 1,
"workout_day": "2019-03-02",
"title": "Swimming",
"description": "",
"completed": true,
"points": 5
}, {
"id": 2,
"workout_day": "2019-03-02",
"title": "Running",
"description": "",
"completed": false,
"points": 0
}, {
"id": 3,
"workout_day": "2019-03-02",
"title": "Rowing",
"description": "",
"completed": true,
"points": 3
},
],
"2019-03-05": [{
"id": 1,
"workout_day": "2019-03-02",
"title": "Swimming",
"description": "",
"completed": false,
"points": 0
}, {
"id": 2,
"workout_day": "2019-03-02",
"title": "Running",
"description": "",
"completed": false,
"points": 0
}, {
"id": 3,
"workout_day": "2019-03-02",
"title": "Rowing",
"description": "",
"completed": true,
"points": 8
},
]
};
var result = {};
for (let key in data) {
result[key] = data[key].reduce(({
workouts = 0,
workouts_completed = 0,
total_points = 0
}, currentValue) => {
return {
workouts: workouts + 1,
workouts_completed: currentValue.completed ? workouts_completed + 1 : workouts_completed,
total_points: total_points + currentValue.points
};
}, {});
}
console.log(result);
const result = {};
for(const [workout_day, entries] of Object.entries(input)) {
result[workout_day] = {
workouts: entries.length,
workouts_completed: entries.reduce((acc, e) => acc + e.completed, 0),
total_points: entries.reduce((acc, e) => acc + e.points, 0),
};
}
Object.entries is quite useful for mapping objects.
const data = {
"2019-03-02": [
{
"id": 1,
"workout_day": "2019-03-02",
"title": "Swimming",
"description": "",
"completed": true,
"points": 5
},
{
"id": 2,
"workout_day": "2019-03-02",
"title": "Running",
"description": "",
"completed": false,
"points": 0
},
{
"id": 3,
"workout_day": "2019-03-02",
"title": "Rowing",
"description": "",
"completed": true,
"points": 3
},
],
"2019-03-05": []
};
function makeReport (report, workout) {
return {
workouts: report.workouts + 1,
workouts_completed: workout.completed ? report.workouts_completed + 1 : report.workouts_completed,
total_points: report.total_points + workout.points
};
}
const out = Object.entries(data).reduce(function (report, [date, workouts]) {
return {
...report,
[date]: workouts.reduce(makeReport, { workouts: 0, workouts_completed: 0, total_points: 0 })
};
}, {});
console.log(out);
which logs:
{ '2019-03-02': { workouts: 3, workouts_completed: 2, total_points: 8 },
'2019-03-05': { workouts: 0, workouts_completed: 0, total_points: 0 } }
Related
I use Redux to store all my products in a list. Displayed thist list looks like:
[
{
"id": 1,
"name": "BLACK TEA",
"supplieruuid": "SLIGRO",
"price": 1.10,
},
{
"id": 2,
"name": "GREEN TEA",
"supplieruuid": "SLIGRO",
"price": 1.10,
},
{
"id": 3,
"name": "PURPLE TEA",
"supplieruuid": "BUNZL",
"price": 1.10,
},
{
"id": 4,
"name": "RAINBOW TEA",
"supplieruuid": "BUNZL",
"price": 1.10,
},
]
I'm using this reduce function to group these products together by key supplieruuid.
const sortedBySupplierUUID = state.entities.cart.list.reduce(
(hash, { ["supplieruuid"]: value, ...rest }) => ({ ...hash, [value]: (hash[value] || []).concat({ ["supplieruuid"]: value, ...rest }) }),
{}
);
return Object.keys(sortedBySupplierUUID).map((key) => ({ title: key, data: sortedBySupplierUUID[key] }));
What this returns is as following:
[
{
title: "SLIGRO",
data: [
{
"id": 1,
"name": "BLACK TEA",
"price": 1.10,
},
{
"id": 2,
"name": "GREEN TEA",
"price": 1.10,
},
],
},
{
title: "BUNZL",
data: [
{
"id": 3,
"name": "PURPLE TEA",
"price": 1.10,
},
{
"id": 4,
"name": "RAINBOW TEA",
"price": 1.10,
},
],
},
]
This all works fine, except for that I a total added to the object which will count up the total price of the items in the "data" array of each object as following:
[
{
title: "SLIGRO",
total: 2.20,
data: [
{
"id": 1,
"name": "BLACK TEA",
"price": 1.10,
},
{
"id": 2,
"name": "GREEN TEA",
"price": 1.10,
},
],
},
{
title: "BUNZL",
total: 2.20,
data: [
{
"id": 3,
"name": "PURPLE TEA",
"price": 1.10,
},
{
"id": 4,
"name": "RAINBOW TEA",
"price": 1.10,
},
],
},
]
How can I achieve this by modifying the reduce function I use?
const selectSortedItems = (state) => {
const sortedBySupplierUUID = state.entities.cart.list.reduce((hash, { ["supplieruuid"]: value, ...rest }) => ({ ...hash, [value]: (hash[value] || []).concat({ ...rest }) }), {});
return Object.keys(selectSortedItems(sortedBySupplierUUID)).map(key => (
{
title: key,
total: sortedBySupplierUUID[key].reduce((acc, cur) => acc + cur.price),
data: sortedBySupplierUUID[key]
})
)};
}
More intuitive way of doing it
const selectSortedItems = (state) => {
const itemsMap = {};
state.entities.cart.list.map((item) => {
if (itemsMap[item.supplieruuid]) {
itemsMap[item.supplieruuid].total += item.price;
itemsMap[item.supplieruuid].data.push(item);
} else {
itemsMap[item.supplieruuid] = {
title: item.supplieruuid,
total: item.price,
data: [item]
}
}
});
return Object.values(itemsMap);
}
I have an array of objects as below. I want to recursively sort this based on the key values
{
"settingsList": [
{
"category1": [
{
"categoryName": "DRIVER",
"description": "DRIVER",
"sequence": 1
},
{
"categoryName": "BALL",
"description": "BALL",
"sequence": 2
},
{
"categoryName": "SAMPLE",
"description": "SAMPLE",
"sequence": 3
},
{
"categoryName": "USER",
"description": "USER",
"sequence": 4
}
]
},
{
"category2": [
{
"paramName": "CPP",
"description": "CPP",
"sequence": 1
},
{
"paramName": "PP",
"description": "PP",
"sequence": 2
},
{
"paramName": "MP",
"description": "MP",
"sequence": 3
}
]
}
{
"source": {
"instanceName": "instance_1"
}
}
]
}
How can I efficiently sort recursively to display it sorted alphabetically on the key values.
Expected output:
{
"settingsList": [
{
"category": [
{
"categoryName": "BALL",
"description": "BALL",
"sequence": 2
},
{
"categoryName": "DRIVER",
"description": "DRIVER",
"sequence": 1
},
{
"categoryName": "SAMPLE",
"description": "SAMPLE",
"sequence": 3
},
{
"categoryName": "USER",
"description": "USER",
"sequence": 4
}
]
},
{
"category2": [
{
"paramName": "CPP",
"description": "CPP",
"sequence": 1
},
{
"paramName": "MP",
"description": "MP",
"sequence": 3
},
{
"paramName": "PP",
"description": "PP",
"sequence": 2
}
]
},
{
"source": {
"instanceName": "instance_1"
}
}
]
}
below is the sample code that was tried
var object = {
"settingsList": [
{
"category1": [
{
"categoryName": "DRIVER",
"description": "DRIVER",
"sequence": 1
},
{
"categoryName": "BALL",
"description": "BALL",
"sequence": 2
},
{
"categoryName": "SAMPLE",
"description": "SAMPLE",
"sequence": 3
},
{
"categoryName": "USER",
"description": "USER",
"sequence": 4
}
]
},
{
"category2": [
{
"paramName": "CPP",
"description": "CPP",
"sequence": 1
},
{
"paramName": "PP",
"description": "PP",
"sequence": 2
},
{
"paramName": "MP",
"description": "MP",
"sequence": 3
}
]
},
{
"source": {
"instanceName": "instance_1"
}
}
]
}
var keys = Object.keys(object);
var sortedKeys = keys.sort((key1, key2)=>{
key1 = key1.toLowerCase();
key2 = key2.toLowerCase();
if(key1 < key2) return -1;
if(key1 > key2) return 1;
return 0;
})
function sortData(object){
var newObject = {},
keys = Object.keys(object);
keys.sort(function(key1, key2){
key1 = key1.toLowerCase();
key2 = key2.toLowerCase();
if(key1 < key2) return -1;
if(key1 > key2) return 1;
return 0;
});
for(var index in keys){
var key = keys[index];
if(typeof object[key] == 'object' && !(object[key] instanceof Array)){
newObject[key] = sortData(object[key]);
} else {
newObject[key] = object[key];
}
}
return newObject;
}
var sortedData=sortData(object)
console.log(sortedData)
....................................................................................................................................................................................................................................................................
What you tried to achieved is called deep sort.
You can use deep-sort-object library as follow :
var sortobject = require('deep-sort-object');
var sortedData = sortobject(object);
console.log(sortedData);
Or if you don't want to use a library, you can use this gist as reference.
Here is an iterative solution using object-scan
// const objectScan = require('object-scan');
const myData = { settingsList: [{ category1: [{ categoryName: 'DRIVER', description: 'DRIVER', sequence: 1 }, { categoryName: 'BALL', description: 'BALL', sequence: 2 }, { categoryName: 'SAMPLE', description: 'SAMPLE', sequence: 3 }, { categoryName: 'USER', description: 'USER', sequence: 4 }] }, { category2: [{ paramName: 'CPP', description: 'CPP', sequence: 1 }, { paramName: 'PP', description: 'PP', sequence: 2 }, { paramName: 'MP', description: 'MP', sequence: 3 }] }, { source: { instanceName: 'instance_1' } }] };
const sort = (data) => {
const logic = {
'settingsList[*].category1': (value) => value.sort((a, b) => a.categoryName.localeCompare(b.categoryName)),
'settingsList[*].category2': (value) => value.sort((a, b) => a.paramName.localeCompare(b.paramName))
};
objectScan(Object.keys(logic), {
filterFn: ({ value, matchedBy }) => {
matchedBy.forEach((needle) => logic[needle](value));
}
})(data);
};
console.log(sort(myData));
// => undefined
console.log(myData);
// => { settingsList: [ { category1: [ { categoryName: 'BALL', description: 'BALL', sequence: 2 }, { categoryName: 'DRIVER', description: 'DRIVER', sequence: 1 }, { categoryName: 'SAMPLE', description: 'SAMPLE', sequence: 3 }, { categoryName: 'USER', description: 'USER', sequence: 4 } ] }, { category2: [ { paramName: 'CPP', description: 'CPP', sequence: 1 }, { paramName: 'MP', description: 'MP', sequence: 3 }, { paramName: 'PP', description: 'PP', sequence: 2 } ] }, { source: { instanceName: 'instance_1' } } ] }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#14.4.0"></script>
Disclaimer: I'm the author of object-scan
How can i make the cart_items like my expetation.. just it no more.. my problem just it :D
i just wanna make my cart_items like this.. hope you are can help me thanks. did I make the wrong method? and one more thing, i wanna make the qty inside the cart_items
this is my expectation
"cart": [
{
"id": 1,
"date": "12/10/2020",
"store": {
"id": 1,
"name": "Dirumah Aja",
"promo": 1
},
"cart_items": [
{
"id": 1,
"product": {
"id": 1,
"name": "Bakso Urat",
"price": 10000,
"promo": {
"nama": "promo"
}
},
"qty": 5
}
]
}
]
and this is what I got
"cart": [
{
"cart_items": {
"name": "Steak Sapi Impor",
"price": "38000",
"stock": "4",
"image": "https://firebasestorage.googleapis.com/v0/b/francise-fb70a.appspot.com/o/steak.jpg?alt=media&token=46e0d769-96d3-440f-8edb-5fce2481ace0",
"promo": 3,
"id": 8,
"qty": 1
},
"store": {
"name": "Amanda Foods Store",
"email": "amanda#food.com",
"store_image": "https://firebasestorage.googleapis.com/v0/b/francise-fb70a.appspot.com/o/full_hd_retina.jpeg?alt=media&token=3e602e86-661b-48ee-9e9c-af9f94a170d1",
"product": [
5,
7,
8,
2
],
"store_promo": 1,
"location": {
"street_name": "Jl. Kebon Gedang II B",
"province": "Jawa Barat",
"city": "Bandung",
"post_code": "40285"
},
"id": 1
},
"date_order": "Nov 03 2020 08:48:03",
"id": 2
}
]
This is my data
data() {
return {
promo_id: [],
promo_partner: [],
products: {},
qty: 1,
cart_items: [
{}
]
};
and this is my method
addToCart() {
const date = (new Date()).toString().split(' ').splice(1,4).join(' ')
this.products.cart_items = this.product;
this.products.cart_items.qty = this.qty;
this.products.store = this.partner;
this.products.date_order = date;
console.log(this.cart_items)
axios
.post("http://localhost:3000/cart/", this.products)
.then(() => {
swal("Belanja Berhasil!", {
icon: "success",
});
})
.catch((error) => console.log(error));
}
}
You need to use .push() to add items to an array. You're replacing the array with this.product.
if (!this.products.cart_items) { // initialize cart_items if necessary
this.products.cart_items = [];
}
this.products.cart_items.push({id: this.product.id, product: this.product, qty: this.qty});
I have 2 arrays of objects: itemsList and itemsFetched. All of the objects inside each array have the same structure (nr of key/values). One of those keys has the same 'meaning' but a different name (item_id on itemsList, id on itemsFetched ). Their values are the same.
I need to filter the itemsList array and leave only the objects that have the item_id value equal to the id value on itemsFetched. Then copy(add) the key/value count from each object on the itemsFetched array (which matches the item_id=id) to the filtered array.
I've a working code but I'm sure it isnt the best way to solve this problem. I've already asked something similar before (regarding the 'filter' part) which solved my problem, but since I had to add the 'count' part after the filtering, I ended up refactoring the whole thing.
itemsList (sample)
[
{
"id": 0,
"name": "Egg",
"img": "http://www.serebii.net/pokemongo/items/egg.png"
},
{
"id": 1,
"name": "Pokeball",
"img": "http://www.serebii.net/pokemongo/items/20pokeballs.png"
},
{
"id": 2,
"name": "Greatball",
"img": "http://www.serebii.net/pokemongo/items/greatball.png"
},
{
"id": 401,
"name": "Incense",
"img": "http://www.serebii.net/pokemongo/items/incense.png"
},
{
"id": 901,
"name": "Incubator (Unlimited)",
"img": "http://www.serebii.net/pokemongo/items/eggincubator.png"
}
]
itemsFetched (sample)
[
{
"item_id": 1,
"count": 50,
"unseen": true
},
{
"item_id": 401,
"count": 2,
"unseen": true
},
{
"item_id": 901,
"count": 1,
"unseen": true
}
]
resultArray (what I want in the end)
[
{
"id": 1,
"name": "Pokeball",
"count": 50,
"img": "http://www.serebii.net/pokemongo/items/20pokeballs.png",
},
{
"id": 401,
"name": "Incense",
"count": 2,
"img": "http://www.serebii.net/pokemongo/items/incense.png"
},
{
"id": 901,
"name": "Incubator (Unlimited)",
"count": 1,
"img": "http://www.serebii.net/pokemongo/items/eggincubator.png"
}
]
my current code (working)
let arr = [];
itemsFetched.forEach((item) => {
itemsList.forEach((item2) => {
if (item.item_id === item2.id) {
arr.push({
"id": item.item_id,
"name": item2.name,
"count": item.count,
"img": item2.img
});
}
});
});
PS: I'm able to use ES6/7 syntax/features.
You can use hash map to reduce Time complexitly, your algorithm is O(m*n), The follow is O(m+n+r)
const itemsMap = itemsList.reduce((map, item) => {
map[item.id] = item
return map
}, {})
const results = itemsFetched
.filter((item) => itemsMap.hasOwnProperty(item.item_id))
.map((item) => ({
id: item.item_id,
name: itemsMap[item.item_id].name,
count: item.count,
img: itemsMap[item.item_id].img,
}))
Use a for ... of loop (an ES6 feature) in conjunction with Array#map.
This makes it much easier to return the merged object the first time you find a match, which is a logically optimization because neither list should contain more than one entry with a given id.
const result = itemsFetched.map(data => {
for (let item of itemsList) {
if (data.item_id === item.id) {
return {
id: item.id,
name: item.name,
count: data.count,
img: item.img
}
}
}
})
Snippet:
const itemsList = [{
"id": 0,
"name": "Egg",
"img": "http://www.serebii.net/pokemongo/items/egg.png"
}, {
"id": 1,
"name": "Pokeball",
"img": "http://www.serebii.net/pokemongo/items/20pokeballs.png"
}, {
"id": 2,
"name": "Greatball",
"img": "http://www.serebii.net/pokemongo/items/greatball.png"
}, {
"id": 401,
"name": "Incense",
"img": "http://www.serebii.net/pokemongo/items/incense.png"
}, {
"id": 901,
"name": "Incubator (Unlimited)",
"img": "http://www.serebii.net/pokemongo/items/eggincubator.png"
}]
const itemsFetched = [{
"item_id": 1,
"count": 50,
"unseen": true
}, {
"item_id": 401,
"count": 2,
"unseen": true
}, {
"item_id": 901,
"count": 1,
"unseen": true
}]
const result = itemsFetched.map(data => {
for (let item of itemsList) {
if (data.item_id === item.id) {
return {
id: item.id,
name: item.name,
count: data.count,
img: item.img
}
}
}
})
console.log(result)
One way to improve is to use for..of statement instead of forEach for the inner loop. This helps break from the loop once the id matches. There is no direct way to break from forEach method.
let arr = [];
itemsFetched.forEach((item) => {
for (let item2 of itemsList) {
if (itemsFetched.item_id === itemsList.id) {
arr.push({
"id": itemsFetched.item_id,
"name": itemsList.name,
"count": itemsFetched.count,
"img": itemsList.img
});
break;
}
}
});
Like this?
var itemsList = [
{
"id": 0,
"name": "Egg",
"img": "http://www.serebii.net/pokemongo/items/egg.png"
},
{
"id": 1,
"name": "Pokeball",
"img": "http://www.serebii.net/pokemongo/items/20pokeballs.png"
},
{
"id": 2,
"name": "Greatball",
"img": "http://www.serebii.net/pokemongo/items/greatball.png"
},
{
"id": 401,
"name": "Incense",
"img": "http://www.serebii.net/pokemongo/items/incense.png"
},
{
"id": 901,
"name": "Incubator (Unlimited)",
"img": "http://www.serebii.net/pokemongo/items/eggincubator.png"
}
];
var itemsFetched = [
{
"item_id": 1,
"count": 50,
"unseen": true
},
{
"item_id": 401,
"count": 2,
"unseen": true
},
{
"item_id": 901,
"count": 1,
"unseen": true
}
]
let arr = [];
itemsFetched.forEach((item) => {
itemsList.forEach((item2) => {
if (item.item_id == item2.id) {
arr.push({
"id": item.item_id,
"name": item2.name,
"count": item.count,
"img": item2.img
});
}
});
});
console.log(arr);
I have an array of objects as below that I read from my database using sequelize ORM:
I want to have all my videos from a section, but the better I can return using sequelize is :
[{
"id": 2,
"name": "Ru",
"subsection": 1,
"Video": {
"id": 11,
"source": "sourrrccrsss22222",
"videoSubSection": 2
}
},
{
"id": 2,
"name": "Ru",
"subsection": 1,
"Video": {
"id": 12,
"source": "sourrrccrsss111",
"videoSubSection": 2
}
},
{
"id": 1,
"name": "Oc",
"subsection": 1,
"Video": {
"id": 13,
"source": "sourrrcc",
"videoSubSection": 1
}
},
{
"id": 1,
"name": "Oc",
"subsection": 1,
"Video": {
"id": 14,
"source": "sourrrcc",
"videoSubSection": 1
}
}]
Is there a way to merge and combine the objects in my array to obtain something like this :
[{
"id": 2,
"name": "Ru",
"subsection": 1,
"Video": [{
"id": 11,
"source": "sourrrccrsss22222",
"videoSubSection": 2
},{
"id": 12,
"source": "sourrrccrsss111",
"videoSubSection": 2
}]
},
{
"id": 1,
"name": "Oc",
"subsection": 1,
"Video": [{
"id": 13,
"source": "sourrrcc",
"videoSubSection": 1
},{
"id": 14,
"source": "sourrrcc",
"videoSubSection": 1
}]
}
The function that approach the most is _.mergeWith(object, sources, customizer) but the main problem I have is that I have on object and need to merge this object.
In plain Javascript, you can use Array#forEach() with a temporary object for the arrays.
var data = [{ id: 2, name: "Ru", subsection: 1, Video: { id: 11, source: "sourrrccrsss22222", VideoSubSection: 2 } }, { id: 2, name: "Ru", subsection: 1, Video: { id: 12, source: "sourrrccrsss111", VideoSubSection: 2 } }, { id: 1, name: "Oc", subsection: 1, Video: { id: 13, source: "sourrrcc", VideoSubSection: 1 } }, { id: 1, name: "Oc", subsection: 1, Video: { id: 14, source: "sourrrcc", VideoSubSection: 1 } }],
merged = function (data) {
var r = [], o = {};
data.forEach(function (a) {
if (!(a.id in o)) {
o[a.id] = [];
r.push({ id: a.id, name: a.name, subsection: a.subsection, Video: o[a.id] });
}
o[a.id].push(a.Video);
});
return r;
}(data);
document.write('<pre>' + JSON.stringify(merged, 0, 4) + '</pre>');
Maybe try transform():
_.transform(data, (result, item) => {
let found;
if ((found = _.find(result, { id: item.id }))) {
found.Video.push(item.Video);
} else {
result.push(_.defaults({ Video: [ item.Video ] }, item));
}
}, []);
Using reduce() would work here as well, but transform() is less verbose.
You can do it this way (test is your db output here)
var result = [];
var map = [];
_.forEach(test, (o) => {
var temp = _.clone(o);
delete o.Video;
if (!_.some(map, o)) {
result.push(_.extend(o, {Video: [temp.Video]}));
map.push(o);
} else {
var index = _.findIndex(map, o);
result[index].Video.push(temp.Video);
}
});
console.log(result); // outputs what you want.