How to group nested objects with the same property values?

Good day to all! Trying to solve a similar problem:

Let's say you have an object with duplicate properties in nested objects
var obj = {
 [0] = {
 title: 'Door',
 color: 'White'
}
 [1] = {
 title: 'Door',
 color: 'White'
}
 [2] = {
 title: 'Door',
 color: 'Black'
}
 [3] = {
 title: 'Door',
 color: 'Black'
}
 [4] = {
 title: 'Door',
 color: 'Grey'
}
}


You need to use them to build a new object of this type
var obj = {
 [0] = {
 title: 'Door',
 color: 'White',
 count: 2
}
 [1] = {
 title: 'Door',
 color: 'Black',
 count: 2
}
 [2] = {
 title: 'Door',
 color: 'Grey',
 count: 1
}
}


P. S. the value of the property "title" can be changed in the same way as "color"
July 2nd 19 at 17:03
2 answers
July 2nd 19 at 17:05
Solution
var obj = [{
 title: 'Door',
 color: 'White'
 }, {
 title: 'Door',
 color: 'White'
 }, {
 title: 'Door',
 color: 'Black'
 }, {
 title: 'Door',
 color: 'Black'
 }, {
 title: 'Door',
 color: 'Grey'
}
];

var r_obj = [];

for (var key in obj) {
 var find = false;

 for (var key2 in r_obj) {
 if (r_obj[key2].title == obj[key].title &&
 r_obj[key2].color == obj[key].color) {
r_obj[key2].count++;
 find = true;
}
}

 if (!find) {
r_obj.push({
 title: obj[key].title
 color: obj[key].color
 count: 1
});
}
}

console.log(r_obj);
July 2nd 19 at 17:07

Find more questions by tags OOPJavaScript