简体   繁体   中英

Group array of objects based on a key and return the new array of objects

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

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);

You can loop through data and search for the index of the item that has the same name but different color (the if statement checks if indexOfFound >= 0 because if an item is not found, findIndex returns -1) mutate the item and then remove the item that was found.

So something like this:

 let data = [{ entityName: "Amazon", color: "red", details: "Hello" }, { entityName: "Amazon", color: "green", details: "World" }, { entityName: "Flipkart", color: "green", details: "1234567" }]; data.forEach(item => { const indexOfFound = data.findIndex(diffItem => diffItem.entityName == item.entityName && diffItem.color !== item.color); if (indexOfFound >= 0) { item.color = "yellow"; item.details = `${item.details} ${data[indexOfFound].details.toLowerCase()}` data.splice(indexOfFound, 1); } }); console.log(data);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM