Home > front end >  how to break object inside array of an object in javascript
how to break object inside array of an object in javascript

Time:03-16

I have a following array:

const test = [{
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: 6,
}]

and i want this

const test = [{a: 1, b: 2, c:3},{d: 4, e:5, f:6}]

CodePudding user response:

Your example

In this particular case you could do it like this.

const input = [{
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: 6,
}]

const { a, b, c, d, e, f } = input[0];

const output = [
    { a: a, b: b, c: c },
    { d: d, e: e, f: f }
]

console.log(input)
console.log(output)

Expected output

[ { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 } ]
[ { a: 1, b: 2, c: 3 }, { d: 4, e: 5, f: 6 } ]

General case

By iterating over the object properties you can also achieve this kind of transformation based on some condition for all input with that shape.

const input = [{
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: 6,
}]

const output = []
input.forEach(elem => {
    // get entries of object which contains keys and values of the JavaScript object
    const entries = Object.entries(elem);

    let curObj = {};
    entries.forEach((entry, index) => {
        curObj[entry[0]] = entry[1]
        // some condition on when to create a new object (e.g. every 3rd property)
        if((index   1) % 3 === 0){
            output.push(curObj);
            curObj = {}
        }
    })
    // in case there are some properties left 
    if(Object.keys(curObj).length !== 0){
        output.push(curObj);
    }
})

console.log("Input")
console.log(input);
console.log("Output")
console.log(output);

This will give you the exact same result as before but it will work with any number of properties within an object and any number of objects in the input array.

Take for instance this input:

const input = [
  {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: 6,
    g: 34,
    h: 23,
    i: 234,
    j: 324,
    k: 3434,
    l: 343,
  },
  {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: 6,
    g: 34,
    h: 23,
    i: 234,
    j: 324,
    k: 3434,
    l: 343,
  },
];

It will result in this output:

Input
[
  {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: 6,
    g: 34,
    h: 23,
    i: 234,
    j: 324,
    k: 3434,
    l: 343
  },
  {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: 6,
    g: 34,
    h: 23,
    i: 234,
    j: 324,
    k: 3434,
    l: 343
  }
]
Output
[
  { a: 1, b: 2, c: 3 },
  { d: 4, e: 5, f: 6 },
  { g: 34, h: 23, i: 234 },
  { j: 324, k: 3434, l: 343 },
  { a: 1, b: 2, c: 3 },
  { d: 4, e: 5, f: 6 },
  { g: 34, h: 23, i: 234 },
  { j: 324, k: 3434, l: 343 }
]
  • Related