I have to create an array of arrays based on some object attributes.
So my object looks like this:
const data = {
projectId: 5,
userIds: [2, 3, 1, 5],
dateIds: [99, 100, 101, 102, 103],
task: 'task',
duration: 8,
description: 'description'
}
Based on the userIds
and dateIds
I have to create an array of arrays with every attribute like this:
[[projectId, userId, dateId, task, duration, description]]
<- this is what every number means
For every userId
and dateId
i have to create a new array.
And based on my example should be like this:
[[5, 2, 99, 'task', 8, 'description'],
[5, 3, 99 , 'task', 8, 'description'],
[5, 1, 99, 'task', 8, 'description'],
[5, 5, 99, 'task', 8, 'description'],
[5, 2, 100, 'task', 8, 'description'],
[5, 3, 100, 'task', 8, 'description']
... etc]]
Hope i explained my issue well. Thank you for your time!
My function:
const data = { projectId: 5, userIds: [2, 3, 1, 5], date: [99, 100, 101, 102], task: 'task', duration: 'duration', description: 'description' } const parentArray = [] data.date.map(object => data.userIds.map(anotherObject => { // console.log(anotherObject, object) parentArray.push([data.projectId, object, anotherObject, data.task, data.duration, data.description]) } )) console.log(parentArray)
const data = { projectId: 5, userIds: [2, 3, 1, 5], dateIds: [99, 100, 101, 102, 103], task: 'task', duration: 8, description: 'description' } const result = data.userIds.map(uid => { return data.dateIds.map(did => [data.projectId, uid, did, data.task, data.duration, data.description]) }).flat(); console.log(result);
Not exactly what you asked for but using your example you can create an array of objects which might add clarity by naming the properties (if some other user needs something like this). Note how I pass in the data
and reference it with this
and loop through the dateId
's. Key is I never have to reference the original array, perhaps making this more maintainable internally;
const data = { projectId: 5, userIds: [2, 3, 1, 5], dateIds: [99, 100, 101, 102, 103], task: 'task', duration: 8, description: 'description' }; let x = []; data.userIds.forEach(function(userid, index) { this.dateIds.map((dateid, idx) => { x.push({ project: this.projectId, user: userid, dateid: dateid, tsk: this.task, dur: this.duration, desc: this.description }); }); }, data); x.forEach(function(el, index, array) { console.log(el); });
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.