2016-07-26 89 views
-1

我在Javascript以下對象:JavaScript對象數組解析問題

Array[11] 
0:"532" 
1:"text-warning" 
2:"51" 
3:"text-warning" 
4:"16" 
5:"muted" 
6:"35" 
7:"text-warning" 
8:"38" 
9:"text-warning" 
10:"106" 

Array[11] 
0:"533" 
1:"text-warning" 
2:"51" 
3:"text-warning" 
4:"16" 
5:"muted" 
6:"35" 
7:"text-success" 
8:"38" 
9:"text-warning" 
10:"106" 

Array[11] 
0:"534" 
1:"text-warning" 
2:"51" 
3:"text-warning" 
4:"16" 
5:"text-warning" 
6:"35" 
7:"text-success" 
8:"38" 
9:"text-warning" 
10:"106" 

我想分析它,並發現如果兩個數值數組中只出現一次。

示例: 「文本成功」 或 「靜音」(如果存在)ONCE返回數組

如果EXIST兩次返回null

如果TRUE返回相應的ID

在上面的例子:

1個數組:是TRUE

Array[11] 
0:"532" 
1:"muted" 
2:"35" 

注:第二個是假的,因爲它的存在兩次

第三屆之一:亦是如此

Array[11] 
0:"534" 
1:"text-success" 
2:"38" 

我一直試圖在過去的幾天裏沒有成功

我有以下JQUERY:但它只是變得獨特的價值,但放棄其他:

我首先需要的ID和相應的ID,以及:

Array[11] 
0:"534" -> main id (needed) 
1:"text-success" 
2:"38" -> company id (needed) 



function singles(array) { 
    for(var index = 0, single = []; index < array.length; index++) { 

     if(array[index] == "text-success" || array[index] == "muted") { 
      single.push(array[index]); 
     } 
    } 
    return single; 
}; 

結果或所需要的輸出:

Array[11] 
    0:"532", 
    1:"muted", 
    2:"35", 

第一個值是在主ID, 所述第二值是唯一的和 所述第三值是唯一的值相應的ID。

+0

哪裏是你的jQuery的? – choz

+1

請將對象/數組添加爲文本文字。 –

+0

@choz它在那裏,請看看 –

回答

0

可以解決:

  • 變換對象數組
  • 檢查重複的元素,然後通過
  • 獨特元素推到新的數組
var obj = { 
0:"532", 
1:"text-warning", 
2:"51", 
3:"text-warning", 
4:"16", 
5:"muted", 
6:"35", 
7:"text-warning", 
8:"38", 
9:"text-warning", 
10:"106" 
}; 


function restUnique(obj){ 
var mix = []; 
var output= []; 
Object.keys(obj).forEach(function(key) { 

    mix[key]=obj[key]; 

}); 

for(var i in mix){ 
    fb=mix.indexOf(mix[i]); 
    fa=mix.lastIndexOf(mix[i]); 
    if(fb===fa){output.push(mix[i]);} 
} 
return output; 
} 
// usage example: 
restUnique(obj); // output : 532,51,16,muted,35,38,106