1

if I had an array of objects such as

const arrOfObj = [
    {
        'a': 'a', 
        'b': 'b', 
        'c': 'c',
        'd': 'd'
    }
 ]

how do I create a new array with an object that has only a and b?

 {
        'a': 'a', 
        'b': 'b'
 }

I've been trying something like

Object.entries(arrOfObjs[0]).filter(x => x[0] !== 'a' && x[0] !== 'b')

but there must be a simpler cleaner way

3
  • What's wrong with the way you already have? Commented Nov 29, 2018 at 16:33
  • I want it to come back out an array of Objects, not an array of arrays Commented Nov 29, 2018 at 16:34
  • "how do I create a new array with only a and b?" That's not an array. Commented Nov 29, 2018 at 16:39

4 Answers 4

4

You can map the array, use destructuring and shorthand property names you're there:

const result = arrOfObj.map(({a, b}) => ({a, b}));

Example:

const arrOfObj = [
  { 'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd' },
  { 'a': 'aa', 'b': 'bb', 'c': 'cc', 'd': 'dd' },
  { 'a': 'aaa', 'b': 'bbb', 'c': 'ccc', 'd': 'ddd' }
];

const result = arrOfObj.map(({a, b}) => ({a, b}));

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

2

Destructuring syntax works nicely for this, as you can see in the other answer. However it requires a and b at the program level. If a and b exist at the data level, for example as values in array, the program would be slightly different

const pick = (o = {}, keys = []) =>
  keys .reduce
    ( (acc, k) => Object .assign (acc, { [k]: o[k] })
    , {}
    )

const print = (...values) =>
  values .forEach (x => console .log (x))

const data =
  { a: 1, b: 2, c: 3 }

print
  ( pick (data, [ 'a', 'b' ])   // { a: 1, b: 2 }
  , pick (data, [ 'c', 'd' ])   // { c: 3, d: undefined }
  , pick (data, [])             // {}
  , data                        // { a: 1, b: 2, c: 3 }
  )

As you can see, data is not mutated by use of pick.

4 Comments

For some time I've been admiring not only the ideas in your answers, but also the layout of your code. I've started incorporating something like it in my personal projects. I was wondering if you've seen any style guides that suggest or enforce something like this. I would love to introduce it to the mega-corp where I work; such a document would make it much more likely to get traction.
The converse of this is if the title is more accurate than the question text, and the OP really wants to remove the c and d properties, then we could write a similar function, omit.
Nice answer for omit. Thanks for the comment Scott. It means a lot coming from you. I haven't seen such a style guide but I've been heavily influenced by Scheme and ML languages like OCaml and Elm. Maybe we could make a draft? I've never done anything like that before. Could be fun :D
I haven't either, but I'd love to try. If you have a GitHub handle, I'll add you to this fresh repository: github.com/CrossEye/style-guide. Feel free to get in touch by email if you like: <myFirstName>@<myLastName>.com. Or we could simply use GitHub issues to discuss it.
1

Your title suggests that you want to remove specific properties, but the text suggests you actually want to keep specific ones. If it's the latter, I would suggest either the solution from ibrahim mahrir or the one from user633183.

But if it's the former, here is an approach similar to the one from user633183 but that creates a clone without the given properties:

const omit = (keys = []) => (o = {}) =>
  Object .keys (o) .reduce
    ( (acc, k) => keys .includes (k)
        ? acc
        : Object .assign (acc, { [k]: o[k] })
    , {}
    )

const print = (...values) =>
  values .forEach (x => console .log (x))

const data =
  { a: 1, b: 2, c: 3, d: 4 }

print
  ( omit ([ 'c', 'd' ]) (data)   // { a: 1, b: 2 }
  , omit ([ 'b' ]) (data)        // { a: 1, c: 3, d: 4 }
  , omit ([ ]) (data)            // { a: 1, b: 2, c: 3, d: 4 }
  , data                         // { a: 1, b: 2, c: 3, d: 4 }
  )

Comments

0

You can delete properties from an object.

const arrOfObj = [
  {
    'a': 'a', 
    'b': 'b', 
    'c': 'c',
    'd': 'd'
  }
];
console.log(arrOfObj.reduce((acc, val) => {
  let v = Object.assign({}, val);
  Object.keys(v).forEach(i => {
    if (i !== 'a' && i !== 'b') {
      delete v[i];
    }
  });
  acc.push(v);
  return acc;
}, []));
console.log(arrOfObj);

** Edited the above to stay more inline with the request.

3 Comments

warning: this mutates the original data, arrOfObj
And further, the OP specifically requested "a new array". I would assume that this also implies that the object in it should be new ones.
Fair enough, didn't read that part, I prefer ibrahim mahrir's answer anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.