Search code examples
javascriptfor-loopjavascript-objects

Leave objects by the list of keys. Pure JS


I want to create a new array of objects without the gender field. Where is the mistake?

let collections = [
    { name: "Tom", gender: "male", age: 12 },
    { name: "Becky", gender: "female", age: 11 },
    { name: "Huck", gender: "male", age: 13 }
  ];
  let newCollections = collections.slice();
  let operations = {
    select: function () {
      let args = [].slice.call(arguments);
      for (let i = 0; i < newCollections.length; i++) {
        for (let key in newCollections[i]) {
          for (let j = 0; j < args.length; j++) {
            if (key !== args[j]) {
              delete key;
              return newCollections;
            } } } } } }; 
const result = operations.select("name", "age");// the list of fields to save

console.log(result);


Solution

  • You could create an omit() function that will return an object without a given property.

    We can then use Array.map() to run each item in the array through this:

    let collections = [ { name: "Tom", gender: "male", age: 12 }, { name: "Becky", gender: "female", age: 11 }, { name: "Huck", gender: "male", age: 13 } ];
    
    function omit(obj, field) {
        return (({ [field]: _, ...result }) => result)(obj);
    }
    
    let newCollections = collections.map(person => omit(person, 'gender'));
    console.log('New collections:', newCollections);
    .as-console-wrapper { max-height: 100% !important; top: 0; }