I have an object like
{
cash: true,
credit: false,
debit: true
}
need to generate a string in this case "Cash, Debit"
I have an object like
{
cash: true,
credit: false,
debit: true
}
need to generate a string in this case "Cash, Debit"
What you can do is, using Object.keys
you can do a filter()
:
var Obj = {
cash: true,
credit: false,
debit: true
};
console.log(
Object.keys(Obj)
.filter(function (key) {
return Obj[key];
})
);
If you want to add some formatting like make it completely string with the first letter capitalised, you can use map()
and join()
function:
var Obj = {
cash: true,
credit: false,
debit: true
};
console.log(
Object.keys(Obj)
.filter(function (key) {
return Obj[key];
})
.map(function (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
})
.join(", ")
);
You could use Object.entries
, filter out the false
, then map to the first element in each entry (uppercasing the first letter), and join the result
const result = Object.entries({cash: true, credit: false, debit: true})
.filter(([_,v]) => v)
.map((v) => v[0].charAt(0).toUpperCase() + v[0].slice(1))
.join(', ')
console.log(result);
Seems you want the list of keys with value equals to true.
E.g
let obj = {
cash: true,
credit: false,
debit: true
}
let arr = [];
for(let prop in obj) {
if(obj(prop) == true) arr.push(prop)
}
console.log(arr) //cash,debit
This is just another variation of the other answers, with included string manipulation for proper grammatical display, tho more verbose than pushing in an array and using .join(', ')
. It is probably not the solution I would employ in the real world, but hopefully does illustrate possibly ways to sort and handle data.
let obj = {
cash: true,
credit: false,
debit: true
},
let finalString = '';
const keys = Object.keys(obj);
keys.forEach((key, index) => {
if (obj[key]) {
const keyString = `${key.capitalize()}';
const comma = index !== keys.length -1 ? ', ' : '';
finalString += (keyString + comma);
}
})
use this function :
function make_string(x){
var string = ""
Object.keys(x).filter(function (key) {
string += x[key] ? `${key},` : '';
})
return string.slice(0, -1)
}
for example :
var payments = {
cash: true,
credit: false,
debit: true
}
console.log(make_string(payments))
var payment = {
cash: true,
credit: false,
debit: true
}
document.getElementById("abc").innerHTML = make_string(payment)
//---- the function to make string from object ----//
function make_string(x){
var string = ""
Object.keys(x).filter(function (key) {
string += x[key] ? `${key},` : '';
})
return string.slice(0, -1)
}
<div id="abc"></div>