skip to Main Content

Is there a way to convert that object into an array in javascript?

{
    "0": {
        "category": "Private",
        "price": "5"
    },
    "1": {
        "category": "VIP",
        "price": "5"
    },
    "2": {
        "category": "Premium",
        "price": "5"
    },
}

expected result :

pricing={[
  { category: "Private", price: 5 },
  { category: "VIP", price: 5 },
  { category: "Premium", price: 5 },
]}

2

Answers


  1. Easiest way would be using Object.values

    const obj = {} // Your object
    
    const array = Object.values(obj).map(item => ({
      category: item.category,
      price: parseInt(item.price)
    }));
    
    console.log(array)
    
    Login or Signup to reply.
  2. Yes, you can convert the given object into an array in JavaScript using the Object.values() method.
    Here’s how you can achieve the expected result:

    const obj = {
        "0": {
            "category": "Private",
            "price": "5"
        },
        "1": {
            "category": "VIP",
            "price": "5"
        },
        "2": {
            "category": "Premium",
            "price": "5"
        },
    };
    
    const result = {
        pricing: Object.values(obj)
    };
    
    console.log(result);
    

    Output:

    {
        pricing: [
            { category: "Private", price: "5" },
            { category: "VIP", price: "5" },
            { category: "Premium", price: "5" }
        ]
    }
    

    In the code above, Object.values(obj) is used to extract the values of the object as an array. Then, the resulting array is assigned to the pricing property of a new object, which matches the expected result.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search