2017-12-18 143 views
1

如何獲取項目重複屬性並將其推送到對象中?打印具有相同屬性的重複項目

比如我有:

var object = { "1" :{"ip": 4}, "2" :{"ip": 3}, "3" :{"ip": 4}, "4" :{"ip": 3}} 

我希望有一個對象或數組,其中我將不得不[[1,3], [2,4]]

+0

請您給出一個有效的預期輸出? –

+0

您的意思是'{[1,3],[2,4]}或'{「4」:[1,3],「3」:[2,4]} – gurvinder372

+0

@ gurvinder372輸出應該是第一個具有相同屬性的所有項目分開 –

回答

2

我期望有一個物體或陣列,其中我將具有{[1,3],[2,4]}

如果指[[1,3], [2,4]] ,然後用reduceObject.values

演示

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

+0

但是如果我想要[{1,3},{2,4}]? –

+0

@Radharu修正了它。 – gurvinder372

+0

看不到它,還沒有修復) –

0

您可以使用reduce()和ES6 Map並返回數組的數組。

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)

+0

你爲什麼在這裏使用'Map'?是關於表現嗎?爲什麼不這樣做,因爲它是由@ gurvinder372完成的? – dhilt

0

您可以使用array#reduceJSON.stringify價值觀爲重點,並添加具有相同價值觀的關鍵。

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

相關問題