Home > front end >  How can I transform a single json object into json array?
How can I transform a single json object into json array?

Time:07-11

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

CodePudding user response:

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.

CodePudding user response:

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

  • Related