Skip to content Skip to sidebar Skip to footer

Add A Unique Id For Each Entry In Json Object

I have a json object as following : I would like for each entry that has the attribute title to add a unique id, so my json object would look like this : and in another version I

Solution 1:

You can use for...in to loop over the object and add unique identifiers.

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

Solution 2:

You could use a closure addId for the callback for iterateing the array and use the inner callback iter for nested arrays.

With the call addId, you can specify an index to start with.

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; }

Post a Comment for "Add A Unique Id For Each Entry In Json Object"