Home > Enterprise >  How to split objects
How to split objects

Time:02-11

How to split objects? I want to split Object. Such as one object per group or two object per group.

obj1: {
    1: 1,
    2: 2,
    3: 3,
},
Split objects into groups(convert obj1 to obj2)
obj2: {
    0: {
            1: 1,
        },
    1: {
            2: 2,
        },
    },
    2: {
            3: 3,
        },
    },
}

CodePudding user response:

You could get the entries, chunk them by getting a new object and assign the array to an object.

function chunk(object, size) {
    const
        entries = Object.entries(object),
        chunks = [];

    let i = 0;

    while (i < entries.length)
        chunks.push(Object.fromEntries(entries.slice(i, i  = size)));

    return Object.assign({}, chunks);
}

console.log(chunk({ 1: 1, 2: 2, 3: 3 }, 1));
console.log(chunk({ 1: 1, 2: 2, 3: 3 }, 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

let obj1 = {
    1 : 1 ,
    2 : 2 ,
    3 : 3
}
let index = 0 ;
let obj2 = {}
for(let key in obj1 ) {
  let temp = {
    
  }
    temp[key] = obj1[key]
       let prev = obj2 ;
    obj2[index] = {
      ...temp
    }
     index  ;
}

Try this code . I hope this solves your issue :)

  • Related