1

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!

1 Answer 1

4

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);

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

1 Comment

Thank you! Worked like a charm.

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.