PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 25, 2022

[FIXED] How can I transform a single json object into json array?

 July 25, 2022     axios, javascript, json, reactjs     No comments   

Issue

My axios api returns a JSON object in the format as follow.

{
    "GROUP": "Group",
    "NTH_PRODUCT_AFTER_M": "Nth Product After M",
    "CART_DISCOUNT": "Cart Discount",
    "EACH_NTH": "Each Nth",
    "BUYX_GETY": "Buy X Get Y",
    "PRODUCT_SET": "Product set",
    "PRODUCT_DISCOUNT": "Product Discount",
    "GET_Y_EACH_SPENT_X": "Get y Each Spent X"
}

but I need to tranform each element in the JSON object into a JSON object of a JSON array into this format below.

[
              { value: "EACH_NTH", label: "Each Nth" },
              { value: "GROUP", label: "Group" },
              { value: "BUYX_GETY", label: "Buy X Get Y" },
              { value: "CART_DISCOUNT", label: "Cart Discount" },
              { value: "NTH_PRODUCT_AFTER_M", label: "Nth Product After M" },
              { value: "PRODUCT_DISCOUNT", label: "Product Discount" },
              { value: "GET_Y_EACH_SPENT_X", label: "Get Y for Each Spend of X" },
              { value: "PRODUCT_SET", label: "Discount on a Product Set" },
            ];

Solution

Use Object.entries() to create an array of key / value pairs then map that to the structure you want

const data = {"GROUP":"Group","NTH_PRODUCT_AFTER_M":"Nth Product After M","CART_DISCOUNT":"Cart Discount","EACH_NTH":"Each Nth","BUYX_GETY":"Buy X Get Y","PRODUCT_SET":"Product set","PRODUCT_DISCOUNT":"Product Discount","GET_Y_EACH_SPENT_X":"Get y Each Spent X"};

const arr = Object.entries(data).map(([value, label]) => ({ value, label }));

console.log(arr);
.as-console-wrapper { max-height: 100% !important; }

The array will be sorted in the order of the keys in the original object.



Answered By - Phil
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing