Rajat Bansal
Rajat Bansal

Reputation: 335

Javascript: Extracting key value pairs from an object and grouping them together in an array of objects

I have an object like this:

const object = { a0: 1, a1: 10, b0: 2, c0: 3,  b1: 20, c1: 30, };

We can assume that the length of new array will be based on the highest end digit of these object keys. So in this case length would be 2. I would like to be able to loop through this object and then have it pushed to an array as a group in following form:

mappedObject = [{a:1, b:2, c:3},{a:10,b:20,c:30}]

So basically all a0,b0 and c0 got grouped together and same for a1, a2 and a3. Note after successful grouping I want to able to remove the digit.

Upvotes: 1

Views: 791

Answers (3)

trincot
trincot

Reputation: 350760

I would not assume that the keys have no other digits in them which are not part of the final few digit(s):

const object = { a0: 1, a1: 10, b0: 2, c0: 3,  b1: 20, c1: 30, };

let arr = [];
Object.entries(object)
      .map(([k, v]) => k.split(/(\d+)$/).slice(0, 2).concat(v))
      .forEach(([k,i,v]) => arr[i] = Object.assign({}, arr[i], { [k]: v }));
   
console.log(arr);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386680

You could separate the keys an assign the value to the right index.

const
    object = { a0: 1, a1: 10, b0: 2, c0: 3,  b1: 20, c1: 30 },
    result = Object
        .entries(object)
        .reduce((r, [k, v]) => {
            const [, key, index] = k.match(/(\D+)(\d+)/);
            if (!r[index]) r[index] = {};
            r[index][key] = v;
            return r;
        }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Rajat Bansal
Rajat Bansal

Reputation: 335

I was overthinking it. All I had to do was just find a way to know the length of potential array and simply loop till that length and access the object like shown below. To know the length of the array in my react app, I had to pass down a prop length.

const mappedObj=[];
for(let i=0;i<2; i++){
 mappedObj.push({a: object[`a${i}`], b: object[`b${i}`], c: object[`c${i}`]});
}

console.log(mappedObj);

Upvotes: 0

Related Questions