我从我的微服务中获取一组布尔值。
"mon": true,
"tues": false,
"wed": false,
"thurs": true,
"fri": false,
"sat": true,
"sun": false,
我需要将布尔值 true 的值转换为数组,例如 以下:
options = ['mon', 'thurs', 'sat']
我该怎么做?
您需要在对象键上使用
filter
作为当天的键:
var day = {
"mon": true,
"tues": false,
"wed": false,
"thurs": true,
"fri": false,
"sat": true,
"sun": false
};
var res = Object.keys(day).filter(key => day[key]);
console.log(res);
您可以过滤键:
const obj = {
"mon": true,
"tues": false,
"wed": false,
"thurs": true,
"fri": false,
"sat": true,
"sun": false,
};
const options = Object.keys(obj).filter(key => obj[key]);
console.log(options);
只是条目和数组解构的另一种方式
let day = {
"mon": true,
"tues": false,
"wed": false,
"thurs": true,
"fri": false,
"sat": true,
"sun": false
};
let result = Object.entries(day).filter(([key, state]) =>state).map(([key]) => key);
console.log(result);