2016-12-05 86 views
-1

我有一個JSON對象如下:添加一個唯一的ID爲JSON對象的每個條目

enter image description here

我想對於一個具有屬性title添加一個唯一的ID每個條目,所以我的JSON對象應該是這樣的:

enter image description here

而在另一個版本我想添加一個唯一的ID爲每個條目,所以它看起來像這樣:

enter image description here

我該怎麼做?

編輯:

這是我的JSON對象:https://api.myjson.com/bins/59prd

+0

使用['對... in'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for .. .in)循環播放對象並添加標識符。 – LuudJacobs

+3

請將代碼/對象添加爲文本,而不是圖片。 –

+0

@NinaScholz,請檢查我的編輯 –

回答

1

您可以使用for...in遍歷所有的對象,並添加唯一標識符。

var iterator = 0; // this is going to be your identifier 

function addIdentifier(target){ 
    target.id = iterator; 
    iterator++; 
} 

function loop(obj){ 

    for(var i in obj){ 

    var c = obj[i];   

    if(typeof c === 'object'){ 

     if(c.length === undefined){ 

     //c is not an array 
     addIdentifier(c); 

     } 

     loop(c); 

    } 

    } 

} 

loop(json); // json is your input object 
+0

我提高你的解決方案,因爲它通過使用遞歸和被分割成可重用的方法更清潔。 –

0

你可以使用一個封閉件addId回調爲iterateing陣列,並使用內回調iter嵌套陣列。

通過電話addId,您可以指定一個索引開始。

function addId(id) { 
 
    return function iter(o) { 
 
     if ('title' in o) { 
 
      o.id = id++; 
 
     } 
 
     Object.keys(o).forEach(function (k) { 
 
      Array.isArray(o[k]) && o[k].forEach(iter); 
 
     }); 
 
    }; 
 
} 
 

 
var data = [{ "Arts": [{ "Performing arts": [{ "Music": [{ "title": "Accompanying" }, { "title": "Chamber music" }, { "title": "Church music" }, { "Conducting": [{ "title": "Choral conducting" }, { "title": "Orchestral conducting" }, { "title": "Wind ensemble conducting" }] }, { "title": "Early music" }, { "title": "Jazz studies" }, { "title": "Musical composition" }, { "title": "Music education" }, { "title": "Music history" }, { "Musicology": [{ "title": "Historical musicology" }, { "title": "Systematic musicology" }] }, { "title": "Ethnomusicology" }, { "title": "Music theory" }, { "title": "Orchestral studies" }, { "Organology": [{ "title": "Organ and historical keyboards" }, { "title": "Piano" }, { "title": "Strings, harp, oud, and guitar" }, { "title": "Singing" }, { "title": "Strings, harp, oud, and guitar" }] }, { "title": "Recording" }] }, { "Dance": [{ "title": "Choreography" }, { "title": "Dance notation" }, { "title": "Ethnochoreology" }, { "title": "History of dance" }] }, { "Television": [{ "title": "Television studies" }] }, { "Theatre": [{ "title": "Acting" }, { "title": "Directing" }, { "title": "Dramaturgy" }, { "title": "History" }, { "title": "Musical theatre" }, { "title": "Playwrighting" }, { "title": "Puppetry" }] }] }] }]; 
 

 
data.forEach(addId(1)) 
 
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

相關問題