转换为json对象标签值格式

时间:2019-02-27 18:38:46

标签: javascript android ios reactjs react-native

我下面是这种类型的对象-

{
2019-02-28 02:36:20: "5 minutes"
2019-02-28 23:59:59: "Today"
2019-03-01 02:31:20: "+1 Day"
2019-03-02 02:31:20: "+2 Days"
2019-03-03 02:31:20: "+3 Days"
2019-03-07 02:31:20: "+1 Week"
2019-03-14 02:31:20: "+2 Weeks"
2019-03-21 02:31:20: "+3 Weeks"
2019-03-28 02:31:20: "+1 Month"
2019-04-28 02:31:20: "+2 Months"
2019-05-28 02:31:20: ">2 Months"
}

and i want to convert it into-
[
{label:'5 minutes', value:'2019-02-28 02:36:20'},
{label:'Today', value:'2019-02-28 23:59:59'},
]

通过使用以下功能,我只能获得键和值,但是我无法创建这种类型的数组,请任何人帮助我

closeDate = Object.values(state.finalRequest.closeDate);
  closeDateKey = Object.keys(state.finalRequest.closeDate);

3 个答案:

答案 0 :(得分:1)

您可以使用Object.entries,然后使用map

以所需的形式映射它

let obj = {"2019-02-28 02:36:20": "5 minutes","2019-02-28 23:59:59": "Today","2019-03-01 02:31:20": "+1 Day","2019-03-02 02:31:20": "+2 Days","2019-03-03 02:31:20": "+3 Days","2019-03-07 02:31:20": "+1 Week","2019-03-14 02:31:20": "+2 Weeks","2019-03-21 02:31:20": "+3 Weeks","2019-03-28 02:31:20": "+1 Month","2019-04-28 02:31:20": "+2 Months","2019-05-28 02:31:20": ">2 Months"}

let op = Object.entries(obj)
         .map(([ label, value ] ) => ({ label, value }))

console.log(op)

答案 1 :(得分:0)

您可以这样做。

首先从对象中提取键,然后在键数组上进行映射,以创建所需对象的新数组。

let values = {
"2019-02-28 02:36:20": "5 minutes",
"2019-02-28 23:59:59": "Today",
"2019-03-01 02:31:20": "+1 Day",
"2019-03-02 02:31:20": "+2 Days",
"2019-03-03 02:31:20": "+3 Days",
"2019-03-07 02:31:20": "+1 Week",
"2019-03-14 02:31:20": "+2 Weeks",
"2019-03-21 02:31:20": "+3 Weeks",
"2019-03-28 02:31:20": "+1 Month",
"2019-04-28 02:31:20": "+2 Months",
"2019-05-28 02:31:20": ">2 Months"
};

// get the keys
let keys = Object.keys(values);
// map the values into want you want
let result = keys.map(key => {
  return {label:values[key], value:key}
})

console.log(result)

答案 2 :(得分:0)

在这里,您可以使用 for ... in 来遍历输入对象的另一种方法:

const input = {
  "2019-02-28 02:36:20": "5 minutes",
  "2019-02-28 23:59:59": "Today",
  "2019-03-01 02:31:20": "+1 Day",
  "2019-03-02 02:31:20": "+2 Days",
  "2019-03-03 02:31:20": "+3 Days",
  "2019-03-07 02:31:20": "+1 Week",
  "2019-03-14 02:31:20": "+2 Weeks",
  "2019-03-21 02:31:20": "+3 Weeks",
  "2019-03-28 02:31:20": "+1 Month",
  "2019-04-28 02:31:20": "+2 Months",
  "2019-05-28 02:31:20": ">2 Months"
};

let res = [];

for (const key in input)
{
    res.push({label:input[key], value:key});
}

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}