2017-09-10 25 views
0

我有一個數組對象,其中的某個鍵的值可能會重複出現。還有另一個屬性的值+常量。我的目標是根據重複的位置添加一個數字。因此,例如,我的陣列看起來像這樣如何查找對象數組中的重複項並調整重複位置的值

[{ 
    "id": "53990XXXX", 
    "components": { 
     "CategorySnippet": "snippet-53990XXXX" 
    } 
}, { 
    "id": "56990XXXX", 
    "components": { 
     "CategorySnippet": "snippet-56990XXXX" 
    } 
}, { 
    "id": "54980XXXX", 
    "components": { 
     "CategorySnippet": "snippet-54980XXXX" 
    } 
}, { 
    "id": "53990XXXX", 
    "components": { 
     "CategorySnippet": "snippet-53990XXXX" 
    } 
}] 

我希望它是這樣

[{ 
     "id": "53990XXXX", 
     "components": { 
      "CategorySnippet": "snippet-53990XXXX" 
     } 
    }, { 
     "id": "56990XXXX", 
     "components": { 
      "CategorySnippet": "snippet-56990XXXX" 
     } 
    }, { 
     "id": "54980XXXX", 
     "components": { 
      "CategorySnippet": "snippet-54980XXXX" 
     } 
    }, { 
     "id": "53990XXXX", 
     "components": { 
      "CategorySnippet": "snippet-53990XXXX_1" 
     } 
    }] 

我應該怎麼做這個用純JS?

+1

我無法找到這兩者之間的區別 – brk

+0

@brk - CategorySnippet「:」snippet-53990XXXX_1「基本上不能在CategorySnippet對象中重複。 – soum

回答

3

可以出現的量存儲在一個地圖是這樣的:

function checkArray(somearray){ 
    var temp = {}; 
    var id; 
    var snippet; 
    for(var i=0; i<somearray.length; i++){ 
     id = somearray[i].id; 
     if(temp[id] == undefined){ 
      temp[id] = 0; 
     }else{ 
      temp[id] += 1; 
      snippet = somearray[i].components.CategorySnippet; 
      somearray[i].components.CategorySnippet = snippet+"_"+temp[id]; 
     } 
    } 
    return somearray; 
} 

編輯:返回原始的修改後的數組

1

您還可以使用reduce

function adjustArray(arr) { 
    return arr.reduce((p, c) => { 
    const s = c.components.CategorySnippet; 

    // If the snippet key doesn't exist in the temp object 
    // create it and set it to zero 
    p.temp[s] = p.temp[s] || 0; 

    // If the snippet temp key is greater than 0, add an extension 
    const ext = p.temp[s] > 0 ? `_${p.temp[s]}` : ''; 

    // Change the CategorySnippet value, merge it back to c 
    // and push the object to the output array 
    Object.assign(c.components, { CategorySnippet: `${s}${ext}`}); 
    p.out.push(c); 

    // Increase the temp value for the next iteration 
    p.temp[s]++; 
    return p; 

    // Return the out array filled with objects 
    }, { out: [], temp: {} }).out; 
} 

adjustArray(arr); 

DEMO