Home > Software engineering >  Converting object to array with objects
Converting object to array with objects

Time:01-31

I need help sorting this out, I tried object.keys with map, but can't get too far, so, I have this object and each key has an array:

const first = {
    "apples": [
        "5.78",
        "3.96",
        "3.71"
    ],
    "oranges": [
        "54.25",
        "41.29",
        "33.44"
    ],
    "cucumbers": [
        "97.28",
        "97.13",
        "95.95"
    ],
    "carrots": [
        "6.48",
        "5.1",
        "4.65"
    ]
}

and I need to sort it out and get a new array of objects like this one:

const second = [
    {
        "apples": "5.78",
        "oranges": "54.25",
        "cucumbers": "97.28",
        "carrots": "6.48"
    },
    {
        "apples": "3.96",
        "oranges": "41.29",
        "cucumbers": "97.13",
        "carrots": "5.1"
    },
    {
        "apples": "3.71",
        "oranges": "33.44",
        "cucumbers": "95.95",
        "carrots": "4.65"
    }
]

Thank you very much!!

CodePudding user response:

Please ensure that you share with us how you attempted to solved this problem first, so that we know what all you've already tried.

That said, we'll help you out this time. You can create the second array using Object.entries():

const first = {
    "apples": [
        "5.78",
        "3.96",
        "3.71"
    ],
    "oranges": [
        "54.25",
        "41.29",
        "33.44"
    ],
    "cucumbers": [
        "97.28",
        "97.13",
        "95.95"
    ],
    "carrots": [
        "6.48",
        "5.1",
        "4.65"
    ]
}

const second = Object.entries(first).reduce((res, [key, arr]) => {
  arr.forEach((val, i) => {
    if (!res[i]) res[i] = {};
    res[i][key] = val;
  });
  return res;
}, []);

console.log(second);

// Output
[
    {
        "apples": "5.78",
        "oranges": "54.25",
        "cucumbers": "97.28",
        "carrots": "6.48"
    },
    {
        "apples": "3.96",
        "oranges": "41.29",
        "cucumbers": "97.13",
        "carrots": "5.1"
    },
    {
        "apples": "3.71",
        "oranges": "33.44",
        "cucumbers": "95.95",
        "carrots": "4.65"
    }
]

CodePudding user response:

const d = {"apples":["5.78","3.96","3.71"],"oranges":["54.25","41.29","33.44"],"cucumbers":["97.28","97.13","95.95"],"carrots":["6.48","5.1","4.65"]}

const r = Object.values(d)[0]
  .map((_,i)=>Object.fromEntries(Object.entries(d).map(([k,v])=>[k,v[i]])))

console.log(r)

  • Related