1

I have an object of arrays say

obj_of_arr = {a : [1,2], b:["foo","bar"]}

and I want to turn it into the equivalent array of objects

arr_of_obj = [{a:1,b:"foo"},{a:2,b:"bar"}]

What is the most elegant way to achieve this? I can "brute force" this but I want to know if there is an elegant way. If it involves jQuery it's fine.

1
  • Could you accept this answer? It would help other users with similar problems. Commented Feb 14, 2023 at 0:49

1 Answer 1

3

Why not just do it with two loops?

Note: If this is the "brute force" way you talked about, then I don't know how to help you. Even if there's some jQuery (or other framework) function that does this, it probably uses a similar construct internally, as those frameworks usually don't have any magical powers that let them be faster or more efficient.

Preview (JSBin)

function obj_to_arr(obj_of_arr) {
    var objects = [];

    for (var prop in obj_of_arr) {
        for (var i = 0; i < obj_of_arr[prop].length; i++) {
            if (typeof(objects[i]) != "object") {
                objects[i] = {};
            }
            objects[i][prop] = obj_of_arr[prop][i];
        }
    }

    return objects;
}

const obj_of_arr = {a : [1,2], b:["foo","bar"]};
console.log(obj_to_arr(obj_of_arr));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.