Search code examples
javascriptarraysobjectdestructuring

Filtering the data from object


I'm trying object destructuring to filter the data with new array but, it gives me the same data.

I would like to filter out object properties in order to have in the new array objects with only the following 3 properties: name, occupation, gender

Trying to get any advice.

const employee = [
  {
    name: 'sam',
    occupation: 'designer',
    gender: 'M',
    email: '[email protected]',
    salary: 40000,
    location: 'Canada'
  },
  {
    name: 'sara',
    occupation: 'developer',
    gender: 'M',
    email: '[email protected]',
    salary: 30000,
    location: 'USA'
  },
];

function filterData(arr) {
  arr.map(( name, occupation, gender ) => ({ name, occupation, gender }));

  return arr
}

console.log(filterData(employee));

Solution

  • So, it looks like you want to "pluck" key-value pairs for each item.

    const employeeRecords = [{
      name: 'sam',
      occupation: 'designer',
      gender: 'M',
      email: '[email protected]',
      salary: 40000,
    }, {
      name: 'sara',
      occupation: 'developer',
      gender: 'M',
      email: '[email protected]',
      salary: 10000,
    }];
    
    const pluckData = (arr) =>
      arr.map(({ name, occupation, gender }) => ({ name, occupation, gender }));
    
    console.log(pluckData(employeeRecords));
    .as-console-wrapper { top: 0; max-height: 100% !important; }

    Alternatively, you could pass in an array of keys to pluck:

    const employeeRecords = [{
      name: 'sam',
      occupation: 'designer',
      gender: 'M',
      email: '[email protected]',
      salary: 40000,
    }, {
      name: 'sara',
      occupation: 'developer',
      gender: 'M',
      email: '[email protected]',
      salary: 10000,
    }];
    
    const pluckData = (arr, ...keys) =>
      arr.map(item =>
        keys.reduce((acc, key) => ({ ...acc, [key]: item[key] }), {}));
    
    console.log(pluckData(employeeRecords, 'name', 'occupation', 'gender'));
    .as-console-wrapper { top: 0; max-height: 100% !important; }