У меня есть объект с несколькими свойствами true / false, мне нужно вернуть массив только с именем свойства с true.
Я пробовал Object.entries, но не знаю, как сейчас создать массив.
const inputs = {
a: true,
b: true,
c: false
}
// result should be ['a','b']
// i have tried so far this one with no success
// const result = Object.entries(inputs).map((x, idx) => console.info(x))



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Object.keys(inputs).filter(key => inputs[key])
Используйте мой JSFiddle для кода.
Используйте метод массива фильтров, описанный MDN как
creates a new array with all elements that pass the test implemented by the provided function
Вызовите его в Object.keys, встроенном массиве для объектов:
returns an array of a given object's property names
Источник: Object.keys ()
Итак, чтобы собрать все вместе, это будет выглядеть так:
const inputs = {
a: true,
b: true,
c: false
}
console.info(inputs); // Output: {a: true, b: true, c: false}
const arr = Object.keys(inputs).filter(keyName => inputs[keyName]);
console.info(arr); // Output: ["a", "b"]
Для предоставления только ключей объекта используйте filter:
Нравится:
const inputs = {
a: true,
b: true,
c: false
};
var true_inputs = Object.keys(inputs).filter(key => inputs[key]);
console.info(true_inputs);Или JQuery map:
const inputs = {
a: true,
b: true,
c: false
};
var true_inputs = $.map(inputs, function(n, i) { if (n) return i });
console.info(true_inputs);<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>Чтобы получить весь объект, используйте for .. in:
Нравится:
const inputs = {
a: true,
b: true,
c: false
};
var true_inputs = {};
for(var key in inputs){
if (inputs[key])
true_inputs[key]=inputs[key];
}
console.info(inputs);
console.info(true_inputs);
Попробуйте
Object.keys(inputs).filter(key => inputs[key]);