我有一個JSON對象如下:添加一個唯一的ID爲JSON對象的每個條目
我想對於一個具有屬性title
添加一個唯一的ID每個條目,所以我的JSON對象應該是這樣的:
而在另一個版本我想添加一個唯一的ID爲每個條目,所以它看起來像這樣:
我該怎麼做?
編輯:
這是我的JSON對象:https://api.myjson.com/bins/59prd
我有一個JSON對象如下:添加一個唯一的ID爲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
回調爲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; }
使用['對... in'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for .. .in)循環播放對象並添加標識符。 – LuudJacobs
請將代碼/對象添加爲文本,而不是圖片。 –
@NinaScholz,請檢查我的編輯 –