Skip to content

Instantly share code, notes, and snippets.

@himynameisdave
Last active June 30, 2016 18:31
Show Gist options
  • Select an option

  • Save himynameisdave/856d3f690c19784480b206bd967f13e8 to your computer and use it in GitHub Desktop.

Select an option

Save himynameisdave/856d3f690c19784480b206bd967f13e8 to your computer and use it in GitHub Desktop.
specify an array of keys you want and an array of objs, should return an array of objects with only specified keys
const objects = [
{
a: 'a',
b: 'b',
c: 'c'
},{
a: 'a',
b: 'b',
c: 'c'
},{
a: 'a',
b: 'b',
c: 'c'
}
];
// I only want these keys
const keysIWant = ['a', 'b'];
const getSanitizedObjects = () => {
// Expected:
// getSanitizedObjects[0] -> { a: 'a', b: 'b' }
// naive approach:
return objects.map(obj => {
return {
a: obj.a,
b: obj.b
}
})
};
@jasonbellamy
Copy link
Copy Markdown

const objects = [
  {
    a: 'one',
    b: 'two',
    c: 'c'
  },{
    a: 'three',
    b: 'four',
    c: 'c'
  },{
    a: 'five',
    b: 'six',
    c: 'c'
  }
];

const extract = (x, xs) => {
  return x.map(y => {
    return xs.map(z => ({ [z]: y[z] }))
  })
}


const extracted = extract(objects, ['a', 'b']);

console.log(extracted[1]);
// => { a: 'three', b: 'four' }

@himynameisdave
Copy link
Copy Markdown
Author

himynameisdave commented Jun 30, 2016

@jasonbellamy returns an array of arrays....

screen shot 2016-06-30 at 2 17 41 pm

womp womp womp thanks for playing try again next time.

A solution that worked:

const extract = (x, xs) => {
    return x.map(y => {
      const obj = {};
      xs.map(z => {
        obj[z] = y[z];
      });
      return obj;
    });
  };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment