The object is :
let ob = {1:‘s’ , 2:‘f’ , 4:‘r’ , 6:‘e’}
and I would like to dynamically add the missing numbers in between to achieve
{1:‘s’ , 2:'f ’ , 3:‘x’ , 4:‘r’ , 5:‘w’ , 6:‘e’}
if there is any library that can help me with such as lodash, it is highly appreciated
I don’t know about lodash, but this is pretty easy in JS:
Just loop through and find the first property that doesn’t exist and insert it.
const addNext = (obj, value) => {
const newObj = { ...obj };
let i = 1;
while (true) {
if (!newObj.hasOwnProperty(i)) {
newObj[i] = value;
return newObj;
}
i++;
}
}
let ob = { 1: 's' , 2: 'f' , 4: 'r' , 6: 'e' };
console.log(ob);
// {1: "s", 2: "f", 4: "r", 6: "e"}
ob = addNext(ob, 'x');
console.log(ob);
// {1: "s", 2: "f", 3: "x", 4: "r", 6: "e"}
ob = addNext(ob, 'w');
console.log(ob);
// {1: "s", 2: "f", 3: "x", 4: "r", 5: "w", 6: "e"}