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



我的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"
}

但是我需要将JSON对象中的每个元素转换为JSON数组的JSON对象,格式如下:

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

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

数组将按照原对象中的键的顺序进行排序。

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

相关内容

  • 没有找到相关文章

最新更新