2

Is there a way to improve this code to convert object to mapped array?

I have came up with this solution, is there a better approach and cleaner?

let productItems =  {
    'Item1': { 
        quantity: 4, 
        name: 4,
        price: 123
    },
    'Item2': { 
        quantity: 1, 
        name: 3,
        price: 144
    },
    'Item3': { 
        quantity: 2, 
        name: 2,
        price: 343
    }
}

let items = [];

for (const item in productItems) {
    const formatItem = {
        "Qty": productItems[item].quantity,
        "Cost": productItems[item].price
    }

    items.push(formatItem);
}

Output:

[ { Qty: 4, Cost: 123 },
  { Qty: 1, Cost: 144 },
  { Qty: 2, Cost: 343 } ]

2 Answers 2

6

You can use Object.values()

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

and Array.prototype.map():

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

let productItems =  {
    'Item1': { 
        quantity: 4, 
        name: 4,
        price: 123
    },
    'Item2': { 
        quantity: 1, 
        name: 3,
        price: 144
    },
    'Item3': { 
        quantity: 2, 
        name: 2,
        price: 343
    }
}

let items = Object.values(productItems).map(i => ({Qty: i.quantity, Cost: i.price}));
console.log(items);

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

Comments

1

Object.values will work fine. in case you want to access the keys and values both you can use Object.entries with map

Object.entries({
'Item1': { 
    quantity: 4, 
    name: 4,
    price: 123
},
'Item2': { 
    quantity: 1, 
    name: 3,
    price: 144
},
'Item3': { 
    quantity: 2, 
    name: 2,
    price: 343
}}).map(([key, {quantity, price}]) => ({Qty: quantity, Cost: price}))

3 Comments

Object.entries(obj) returns an array of arrays. The example you've provided will not work as expected. It's easy to fix with array destructuring though: [key, item] => (...)
This is still wrong. You should read the documentation for Object.entries() and test out your code before posting it.
I am extremely sorry, this is embarrassing. I have updated the answer

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.