[英]add a unique id for each entry in json object
我有一個json對象,如下所示:
我想要為每個具有屬性title
條目添加唯一的ID,因此我的json對象將如下所示:
在另一個版本中,我想為每個條目添加一個唯一的ID,因此它看起來像這樣:
我怎樣才能做到這一點 ?
這是我的json對象: https : //api.myjson.com/bins/59prd
您可以使用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
您可以對回調使用閉包addId
來迭代數組,而對嵌套數組使用內部回調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; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.