How can I group an array of objects by key?
Timo's answer is how I would do it. Simple _.groupBy
, and allow some duplications in the objects in the grouped structure.
However the OP also asked for the duplicate make
keys to be removed. If you wanted to go all the way:
var grouped = _.mapValues(_.groupBy(cars, 'make'),
clist => clist.map(car => _.omit(car, 'make')));
console.log(grouped);
Yields:
{ audi:
[ { model: 'r8', year: '2012' },
{ model: 'rs5', year: '2013' } ],
ford:
[ { model: 'mustang', year: '2012' },
{ model: 'fusion', year: '2015' } ],
kia:
[ { model: 'optima', year: '2012' } ]
}
If you wanted to do this using Underscore.js, note that its version of _.mapValues
is called _.mapObject
.
Most efficient method to groupby on an array of objects
If you want to avoid external libraries, you can concisely implement a vanilla version of groupBy()
like so:
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
console.log(groupBy(['one', 'two', 'three'], 'length'));
// => {"3": ["one", "two"], "5": ["three"]}
How to group array of objects by certain property values
A back to the future answer :
Not yet supported by lot of browsers but will come soon (Stage 3 for TC39) and already available in polyfill core-js) is the new groupBy
method on the array object.
This will allows you to do it directly like this :
employees.groupBy(employee => employee.company);
or even :
employees.groupBy(({company}) => company);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/groupBy
How to group items in an array by property using reduce and return an array of new objects
You should be able to do this in a few lines using reduce, we create a map using the Subdomain name as the key, then we'll use Object.values to turn the resulting object into an array.
For example:
const relatedSites = [ { "SubdomainName": "client1", "ClientName": "Eastern Region", "ClientAlias": "eastern-region" }, { "SubdomainName": "client1", "ClientName": "City of Knox", "ClientAlias": "knox" }, { "SubdomainName": "client2", "ClientName": "Eastern Region", "ClientAlias": "eastern-region" }, { "SubdomainName": "client2", "ClientName": "City of Knox", "ClientAlias": "knox" } ];
const result = Object.values(relatedSites.reduce((acc, el) => {
acc[el.SubdomainName] = acc[el.SubdomainName] || { title: el.SubdomainName, links: [] };
acc[el.SubdomainName].links.push({ url: `https://${el.SubdomainName}.com/${el.ClientAlias}`, displayText: el.ClientName });
return acc;
}, {}))
console.log(result)
Group array of objects by key where key is an array
This uses Array.prototype.reduce and Array.prototype.forEach
{
const data = [
{
"name": "Apple",
"tags": ["fruits"]
},
{
"name": "Orange",
"tags": ["fruits"]
},
{
"name": "Tomato",
"tags": ["fruits", "vegetables"]
}
]
const groupedData = data.reduce((carry, element) => {
element.tags.forEach(tag => {
carry[tag] = carry[tag] || []
carry[tag].push({...element})
})
return carry;
}, {})
console.log(groupedData)
}
javascript to group array of objects by key
You can try the below approach to do so. Hope it helps
Loop through the array
and it's items. If the key already exists inside the outputObj
object push the new value into the respective array, else simply create a new array with that key and value (outputObj[key] = [item[key]]
).
Working code:
const array = [{
'red': 50,
'green': 99,
'blue': 66
},
{
'blue': 65,
'red': 88
},
{
'green': 9,
'blue': 6
},
{
'red': 650,
'green': 959,
'blue': 663
},
];
//Method 1
const outputObj = {};
array.forEach(item => {
Object.keys(item).forEach(key => {
if (key in outputObj) {
outputObj[key].push(item[key])
} else {
outputObj[key] = [item[key]]
}
})
})
console.log(outputObj)
//Method 2
const finalObj = array.reduce((acc, curr) => {
const obj = Object.keys(acc).length ? acc : {}
Object.keys(curr).forEach(key => {
if (key in obj) {
obj[key].push(curr[key])
} else {
obj[key] = [curr[key]]
}
})
return obj;
}, {})
console.log(finalObj)
How to group an array of objects by key?
Using array reduce you can iterate data and calculate result object.
const array = [
{ 'red': [ { height: 50 } ] },
{ 'green': [ { height: 20 } ] },
{ 'blue': [ { height: 30 } ] },
{ 'blue': [ { height: 40 } ] },
{ 'red': [ { height: 10 } ] },
{ 'green': [ { height: 60 } ] }
];
const res = array.reduce((acc, element) => {
// Extract key and height value array
const [key, heightValue] = Object.entries(element)[0];
// Get or create if non-exist, and push height value from array, index 0
(acc[key] || (acc[key] = [])).push(heightValue[0]);
return acc;
}, {});
console.log(res);
Group objects from an array of objects based on two or more keys and from an array of dynamically collected values
You can simply use a 'group-by' with a compound key of the specified properties.
Here calling map()
and join()
on your uniqueKeys
array for each iterated object to generate the compound key, then retrieving or initializing the property using logical nullish assignment (??=) before pushing the object to it. The result is the Object.values()
of the grouped object.
const dataSet = [{ lastName: 'Jones', course: 'Standards', gradDate: '12/12/2022' }, { lastName: 'Smith', course: 'Standards', gradDate: '12/12/2022' }, { lastName: 'Martinez', course: 'Maths', gradDate: '12/12/2022' }, { lastName: 'Santiago', course: 'Photography', gradDate: '12/11/2022' }, { lastName: 'Alexi', course: 'Photography', gradDate: '12/11/2022' }];
const uniqueKeys = ['course', 'gradDate'];
const grouped = {};
for (const o of dataSet) {
const key = uniqueKeys.map(k => o[k]).join('_');
(grouped[key] ??= []).push(o);
}
const result = Object.values(grouped)
console.log(result);
How can I group an array of objects by key and create another object inside
Expecting 'color' : { 'Blue','Yellow' }
in your output is wrong. Objects are key-value pairs of data.
Instead, you want color
to be an array. I adjusted your code:
build.forEach(pr => {
if (pr.Product in result) {
result[pr['Product']]['Color'].push(pr['Color']);
} else {
result[pr['Product']] = {
'Product': pr['Product'],
'Color': [pr['Color']]
}
}
});
Now think about how you can prevent duplicate values in the array. @Lissy93's answer helps with that by using findIndex
.
Related Topics
Is There a Cross-Browser Onload Event When Clicking the Back Button
Do Let Statements Create Properties on the Global Object
Enter Data into a Custom-Handled Input Field
Is JavaScript'S "New" Keyword Considered Harmful
Trigger a Button Click With JavaScript on the Enter Key in a Text Box
How to Disable Right Click on My Web Page
Use Async Await With Array.Map
How to Prevent a Parent'S Onclick Event from Firing When a Child Anchor Is Clicked
In JavaScript, Does It Make a Difference If I Call a Function With Parentheses
Access Java/Servlet/Jsp/Jstl/El Variables in JavaScript
How to Check That a Number Is Float or Integer
What Do Parentheses Surrounding an Object/Function/Class Declaration Mean
How to Interpolate Variables in Strings in JavaScript, Without Concatenation
Usage of the Backtick Character (') in JavaScript