Skip to content
Advertisement

How can I convert an indexed JavaScript object to an array of objects?

I have an object that looks like this:

obj = {
"price": {0: "10.00", 1: "15.00", 2: "6.00"},
"serialNumber": {0: 1000, 1: 2000, 2: 3000}
}

I’m trying to convert it into an array of objects so I can do obj.map((obj, idx)=>{//display obj.price and obj.serialNumber//}), so I want to convert obj into an array like this:

obj_array = [{"price":"10.00", "serialNumber": 1000}, {"price":"15.00", "serialNumber": 2000},{"price":"6.00", "serialNumber": 3000}]

I initially used array = Object.values(obj['serialNumber']) to just get serialNumber, but due to the way Object.values works, I can’t just do array = Object.values(obj['serialNumber','price']) to get both. The values() function will ignore the serialNumber field and just make an array of prices. Any help would be appreciated!

Advertisement

Answer

You can use array#reduce with Object.entries() to convert your object to array.

const obj = { "price": { 0: "10.00", 1: "15.00", 2: "6.00" }, "serialNumber": { 0: 1000, 1: 2000, 2: 3000 } },
      result = Object.entries(obj).reduce((r,[key, value]) => {
        Object.values(value).forEach((val, i) => {
          r[i] = {...(r[i] || {}), [key]: val};
        });
        return r;
      },[]);
console.log(result);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement