Issue
I am having the below array of object on which I want to perform group based on entity name and I have see if two objects have same entity Name if yes then I have to see the color if color of both objects are same then I have to group them into one and combine the details of both.
If entity Name of two objects are same and color is different then I have to group them and set color as yellow and have to combine the details and return back the new array of objects.
let data = [
{entityName: "Amazon", color: "red", details: "Hello"}
{entityName: "Amazon", color: "green", details: "World"}
{entityName: "Flipkart", color: "green", details: "1234567"}
]
My excepted output from the above array should be this.
result = [
{entityName: "Amazon", color: "yellow", details: "Hello world"}
{entityName: "Flipkart", color: "green", details: "1234567"}
]
Could anyone please tell me how can I do it?
Solution
You can just iterate over items and find a matching item and implement your logic.
let data = [{
entityName: "Amazon",
color: "red",
details: "Hello"
},
{
entityName: "Amazon",
color: "green",
details: "World"
},
{
entityName: "Flipkart",
color: "green",
details: "1234567"
}
];
var result = [];
for (const value of data) {
const item = result.find(f => f.entityName === value.entityName);
if (!item) {
result.push(value);
} else {
if (item.color !== value.color) {
item.color = 'yellow';
}
item.details += ' ' + value.details;
}
}
console.log(result);
Answered By - Nikhil Patil
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.