Reputation: 441
const prefer={"cs":{"c1":true,"c2":true,"c3":false,"c4":true}}
setArray((prevArray)=>{
return prevArray.filter(function(array){
//code here
})
});
I want to set array on the basis of prefer object, like if c1 is true then is want to add it in the array Do I need to initialize the array too? In above example array=["c1","c2","c4"] . Also do we need filter method or can we use some other method
Upvotes: 0
Views: 57
Reputation: 3434
This is sort of convoluted, but it works:
const prefer = {
"c1": true,
"c2": true,
"c3": false,
"c4": true
}
var setArray = ( prevArray ) => {
return Object.keys(prevArray).filter(function(val, i) {
if ( prevArray[Object.keys(prevArray)[i]] ) return Object.keys(prevArray)[i];
})
};
console.log( setArray(prefer) );
Upvotes: 1
Reputation: 8947
You can express it as follows,
const prefer = { "c1":true, "c2":true, "c3":false, "c4":true }
const output = Object.entries(prefer)
.filter(([, value]) => value) // !!value or Boolean(value) to coerce
.map(([key]) => key)
console.log(output)
Upvotes: 1
Reputation: 8135
You can use for-in loop to iterate map/object
const prefer = { c1: true, c2: true, c3: false, c4: true };
let arr = [];
for (let key in prefer) {
if (prefer[key]) arr.push(key); // modify how u want to save
// arr.push({ [key]: prefer[key] }); // if u want key and value
}
console.log(arr);
Upvotes: 1