I have an array of objects, Where I need to compare "taskId" & "resourceId" of its own array of objects and push the result in a new array. Here is my array
data = [{
"resourceId":1234
"taskId":5001
"taskName":"Test task1"
},
{
"resourceId":1234
"taskId":5001
"taskName":"Test task2"
}
{
"resourceId":1234
"taskId":5002
"taskName":"Test task3"
},
{
"resourceId":1234
"taskId":5001
"taskName":"Test task4"
},
{
"resourceId":5678
"taskId":5003
"taskName":"Test task5"
},
{
"resourceId":5678
"taskId":5004
"taskName":"Test task6"
}
]
Please help me to build this logic. I appreciate your efforts in advance.
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
var result = data.reduce(function (r, a) {
var value = a.resourceId.toString().concat(a.taskId);
r[value] = r[value] || [];
r[value].push(a);
return r;
}, Object.create(null));
This will result the new array as shown below, you can modify the key name(array names) as required
JS Fiddle: https://jsfiddle.net/2cpe3ts6/
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments