0

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

rajithShetty
  • 311
  • 1
  • 3
  • 13
  • Does this answer your question? [Filter object properties by key in ES6](https://stackoverflow.com/questions/38750705/filter-object-properties-by-key-in-es6) – Vivek Molkar Mar 28 '20 at 06:33

3 Answers3

1

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);
xdeepakv
  • 7,835
  • 2
  • 22
  • 32
1

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)
Avin Kavish
  • 8,317
  • 1
  • 21
  • 36
1

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) );
thingEvery
  • 3,368
  • 1
  • 19
  • 25