Skip to content Skip to sidebar Skip to footer

Add An Element At The End Of A List Of Objects In Javascript

I have a list like this as an input: {value: 1, rest: {value: 2, rest: null}} I want to add an element to the list and place it in order to have this output: {value: 1, rest: {val

Solution 1:

You can use for loop here and when i is last object or when rest is null add new object and break loop.

var obj = {value: 1, rest: {value: 2, rest: null}}

functionadd(elem, list) {
  for (var i = obj; i; i = i.rest) {
    if (i.rest == null) {
      i.rest = { value: elem,rest: null}
      break;
    }
  }
}

add(3, obj)
console.log(obj)

Solution 2:

Try this. I made a recursive function.

functionprepend(elem, list){
   if (list.rest == null)
      list.rest = {value:elem, rest:null};
   elseprepend(elem, list.rest);
   return list;
}

This function can be used in all cases.

Solution 3:

functionappend(list, item){
    if(list.rest == null)
    list.rest = item;
   elseappend(list.rest, item)
}

Solution 4:

What you can do is use an array of objects and use append() in the array

Solution 5:

You could iterate through the rest objects and assign then the new object to the last.

functionprepend(elem, list) {
    var object = list;
    while (object.rest) {
        object = object.rest;
    }
    object.rest  = { value: elem, rest: null };
    return list;
}

console.log(prepend(3, { value: 1, rest: { value: 2, rest: null } }));

Post a Comment for "Add An Element At The End Of A List Of Objects In Javascript"