简体   繁体   中英

How can I transform a single json object into json array?

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" },
            ];

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.

 obj = { "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" } arr=[]; for (k in obj) {arr.push({value:k, label:obj[k]})} console.log(arr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM