Reputation: 13
How can I get items duplicate properties and push it in the object?
For example I have:
var object = { "1" :{"ip": 4}, "2" :{"ip": 3}, "3" :{"ip": 4}, "4" :{"ip": 3}}
I expect to have an object or array where I will have [[1,3], [2,4]]
Upvotes: 1
Views: 78
Reputation: 68393
I expect to have an object or array where I will have {[1,3], [2,4]}
If you meant [[1,3], [2,4]]
, then use reduce
and Object.values
Demo
var object = { "1" :{"ip": 4}, "2" :{"ip": 3}, "3" :{"ip": 4}, "4" :{"ip": 3}};
var output = Object.values(Object.keys( object ).reduce( function( a, b){
var key = object[ b ].ip; //key to be used for grouping the values
a[ key ] = a[ key ] || [];
a[ key ].push( Number(b) );
return a;
} ,{}));
console.log( output.reverse() );
Upvotes: 2
Reputation: 22534
You can use array#reduce
and JSON.stringify
the values as key and add the key which have the same values.
var object = { "1" :{"ip": 4}, "2" :{"ip": 3}, "3" :{"ip": 4}, "4" :{"ip": 3}};
var result = Object.keys(object).reduce((map,key) => {
var k = JSON.stringify(object[key]);
map[k] = map[k] || [];
map[k].push(key);
return map;
},{});
var output = Object.values(result);
console.log(output);
Upvotes: 0
Reputation: 122047
You can use reduce()
and ES6 Map
and return array of arrays.
var object = { "1" :{"ip": 4}, "2" :{"ip": 3}, "3" :{"ip": 4}, "4" :{"ip": 3}}
var result = [...Object.keys(object).reduce((r, e) => {
let ip = object[e].ip
if(!r.get(ip)) r.set(ip, [e]);
else r.get(ip).push(e);
return r;
}, new Map).values()];
console.log(result)
Upvotes: 0