Javascript: Show data in array if one element is showable

I'm just new at javascript and currently working with arrays and objects.

Can somebody help me to get the data if the searchble is true in columns. I have columns in array

let columns = [
 {
   data: "id",
   searchable: false
 },
 {

   data: "first_name",
   searchable: true
 },
 {
   data: "last_name",
   searchable: true
 }
];
let filter = {
  target: columns, // if searhable is true
};

If I console log the filter. It will look like this. Result:

{
target: [
  0: "first_name"
  1: "last_name"
  ]
}

2 answers

  • answered 2019-10-08 03:05 Jonas Woo

    const columns = [{
        data: "id",
        searchable: false
      },
      {
    
        data: "first_name",
        searchable: true
      },
      {
        data: "last_name",
        searchable: true
      }
    ];
    
    
    let filter = {
      target: []
    };
    
    for (let i = 0; i < columns.length; i++) {
      if (columns[i].searchable) {
        filter.target.push(columns[i].data);
      }
    }
    console.log(filter);

  • answered 2019-10-08 03:11 wentjun

    A one-liner solution, with Array.filter() and Array.map().

    const columns = [
     {
       data: "id",
       searchable: false
     },
     {
    
       data: "first_name",
       searchable: true
     },
     {
       data: "last_name",
       searchable: true
     }
    ];
    
    const filter = {
      target: columns,
    };
    
    const result = columns.filter(column => column.searchable).map(column => column.data);
    filter.target = result;
    
    console.log(filter);