This question has already been answered:

Good day to all.
Trying to solve the problem:

Suppose there is an object with duplicate properties of nested objects:

var obj = { [0] = { title: 'Дверь', color: 'Белая' } [1] = { title: 'Дверь', color: 'Белая' } [2] = { title: 'Дверь', color: 'Черная' } [3] = { title: 'Дверь', color: 'Черная' } [4] = { title: 'Дверь', color: 'Серая' } } 

It is necessary to build on this basis a new object of this type:

 var obj = { [0] = { title: 'Дверь', color: 'Белая', count: 2 } [1] = { title: 'Дверь', color: 'Черная', count: 2 } [2] = { title: 'Дверь', color: 'Серая', count: 1 } } 

PS The value of the title property can be changed in the same way as color .

Reported as duplicate by user207618, Grundy javascript Nov 14 '16 at 13:42 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Great, where is your decision? - user207618
  • I bet you got php involved here! In javascript, all these entries are syntactically incorrect - Grundy
  • @Grundy, better not find fault with the error, but help - ask for a price, since the vehicle thinks that there is freelancing. - user207618
  • one
    @Other, I would close as a duplicate: this or that - Grundy
  • one
    If you can decide, write a solution, translate here can help. - user207618

1 answer 1

You will need a function that compares objects (correct if any keys need to be ignored or compared otherwise):

 function equals(a, b){ for (var n in a) if (n != 'count' && a.hasOwnProperty(n) && (!b.hasOwnProperty(n) || a[n] != b[n])){ return false; } for (var n in b) if (n != 'count' && !a.hasOwnProperty(n)){ return false; } return true; } 

And then:

 obj.reduce((a, b) => (a.some(x => equals(x, b) && ++x.count) || a.push((b.count = 1, b)), a), []) 

Without abbreviations and switch functions:

 obj.reduce(function (a, b){ if (!a.some(function (x){ if (equals(x, b)){ ++x.count; return true; } return false })){ b.count = 1; a.push(b); } return a }, []);