godsplane
@godsplane

Можно ли как то выводить свойства объекта только со значением true?

let procent = {
    email : false,
    phone : false,
    mail : false
  }

Такой объект. Я хочу менять в нем значение с тру на фолс, если какая то из радиокнопок включена (каждая привязана к свойству объекта)
Можно ли сделать такую проверку, что если одно из свойств объекта true, то выводится свойство со значением true?
Наподобие:
procent.СВОЙСТВОСОЗНАЧЕНИЕМTRUE
  • Вопрос задан
  • 306 просмотров
Пригласить эксперта
Ответы на вопрос 3
@historydev Куратор тега JavaScript
Острая аллергия на анимешников
if(1 === 1) procent.email = true;
Ответ написан
Комментировать
coderisimo
@coderisimo Куратор тега JavaScript
Можно ли сделать такую проверку, что если один из объектов true, то он работает?
что?? ))
Ответ написан
john36allTa
@john36allTa
alien glow of a dirty mind
//Если хоть одно из свойств true то true
Object.prototype.hasSomeTrue = function(){ 
    return Object.values(this).some(prop => prop === true)
}
// Вернуть свойства, которые true
Object.prototype.getPositiveProperties = function (){
    return Object.keys(this).reduce((result, key) => { 
         if (this[key] === true) result[key] = true
         return result
    }, {})
}

Use:
console.log(procent.hasSomeTrue())
//false
procent.email = true
console.log(procent.hasSomeTrue())
//true
console.log(procent.getPositiveProperties())
//{ "email" : true }

Во втором случае посерьёзнее наверное(потому что со вложенными объектами/массивами будет лажа/фича?) будет так:
Object.prototype.filter = function(handler){
	return Object.keys(this).reduce((result,key) => {
		if (handler(this[key],key,this)) 
			result[key] = this[key]
		return result
  }, {})
}

let procent = {
	email : false,
	phone : true,
	mail : false
}

console.log(procent.filter(value => value === true))
//{ "phone" : true }


И лажу с не примитивами(фичу?) в этом случае можно поправить
Object.prototype.filter = function(handler){
	return Object.keys(this).reduce((result,key) => {
		if (handler(this[key],key,this)){
			const kind = Object.prototype.toString.call(this[key]).match(/(\w+)\]$/)[1]
			result[key] = kind === 'Object' ? Object.assign({}, this[key]) : kind === 'Array' ? [...this[key]] : this[key]
    }
		return result
  }, {})
}

Да и ещё типы прикрутить в передачу к handler сразу для удобства, вобщем адаптировать объектам можно массивные map/reduce/filter/some/every...
Object.prototype.filter = function(handler){
	return Object.keys(this).reduce((result,key) => {
		const kind = Object.prototype.toString.call(this[key]).match(/(\w+)\]$/)[1]
		if (handler(this[key],key,kind,this))
			result[key] = kind === 'Object' ? Object.assign({}, this[key]) : kind === 'Array' ? [...this[key]] : this[key]
		return result
  }, {})
}

let procent = {
	email : false,
	phone : true,
	mail : false,
	arr: [1,2,3],
	obj: {a:1,b:2}
}
console.log(procent.filter((v,k,t)=>t==='Boolean'))
//{ "email" : false, "phone" : true, "mail" : false }
console.log(procent.filter(v=>v===true))
//{ "phone" : true }
console.log(procent.filter((v,k,t)=>t==='Object'))
//{ "obj" : { "a" : 1, "b" : 2 } }

В итоге получился такой простенький прототип
Object.prototype.kind = function(){
	return Object.prototype.toString.call(this).match(/(\w+)\]$/)[1]
}
Object.prototype.copy = function(){
	switch (this.kind()){
		case 'Object': return Object.assign({}, this)
			break
		case 'Array': return [...this]
			break;
		//case 'Function': ?
		default: return this
	}
}

Object.prototype.filter = function(handler){
	return Object.keys(this).reduce((result,key) => {
		if (handler(this[key],key,this))
			result[key] = this[key].copy()
		return result
  }, {})
}
Object.prototype.map = function (handler){
	return Object.keys(this).reduce((result, key) => {
		result[key] = handler(this[key],key,this).copy()
		return result
	}, {})
}
Object.prototype.every = function (handler){
	for(key in this)
		if (!handler(this[key],key,this))
			return false
	return true
}
Object.prototype.some = function (handler){
	for(key in this)
		if (handler(this[key],key,this))
			return true
	return false
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы