[英]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.