skip to Main Content

Fill a empty value of a key-value pair with the last value of the previous key.

myitems = {
 'items1': [{first:true, second:false}, {first:true, second:true}],
 'items2': [], //should be filled with {first:true, second:true}
 'items3': [], //should be filled with {first:true, second:true}
 'items4': [{first:true, second:false}, {first:true, second:true}],
 'items5': [{first:false, second:true}],
 'items6': [], //should be filled with {first:false, second:true}
 'items7': [{first:true, second:true}],
}

2

Answers


  1. You can do something like this to achieve that.

    let lastValue = null;
    
    for (const key in myitems) {
      if (myitems[key].length === 0) { // check if value array is empty or not
        // if yes, then
        // check if we have lastValue something, then set that into the current value of `key`
        if (lastValue !== null) {      
          myitems[key] = [lastValue];
        }
      } else {
        lastValue = myitems[key][myitems[key].length - 1];
        // `myitems[key][myitems[key].length - 1]` will give us the last entry in value array
        // we are storing this into our lastValue so that we could use it in future iterations, if we require
      }
    }
    
    Login or Signup to reply.
  2. let myitems = {
      'items1': [{
        first: true,
        second: false
      }, {
        first: true,
        second: true
      }],
      'items2': [],
      'items3': [],
      'items4': [{
        first: true,
        second: false
      }, {
        first: true,
        second: true
      }],
      'items5': [{
        first: false,
        second: true
      }],
      'items6': [],
      'items7': [{
        first: true,
        second: true
      }],
    };
    
    let obj = {};
    let previous;
    for (let x in myitems) {
      if (myitems[x].length) {
        obj[x] = myitems[x];
        previous = myitems[x].slice(-1);
      } else {
        obj[x] = previous;
      }
    }
    console.log(JSON.parse(JSON.stringify(obj)));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search