代码之家  ›  专栏  ›  技术社区  ›  Vodka

如何将单个json对象转换为json数组?

  •  -2
  • Vodka  · 技术社区  · 2 年前

    我的axios api返回一个JSON对象,格式如下。

    {
        "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"
    }
    

    [
                  { 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" },
                ];
    
    2 回复  |  直到 2 年前
        1
  •  2
  •   Phil Moon    2 年前

    使用 Object.entries()

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

    数组将按原始对象中键的顺序排序。

        2
  •  0
  •   selbie    2 年前

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