我从微服务中获取了一组布尔值。
"mon": true,
"tues": false,
"wed": false,
"thurs": true,
"fri": false,
"sat": true,
"sun": false,
我需要将布尔值true的值转换为数组 以下:
options = ['mon', 'thurs', 'sat']
我该怎么办?
答案 0 :(得分:2)
您需要在对象键上使用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);
答案 1 :(得分:0)
您可以过滤键:
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);
答案 2 :(得分:0)
条目和数组解构的另一种方式
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);