0

I am trying to return new object with selected keys - reqProps. I managed to do it with fixes props prop1, prop3 and now want to be able to pass reqProps array values to replace prop1, prop3. I tried function, and string literals and few 'hacks'. None of them worked

const data = [
  {
    prop1: 1,
    prop2: 2,
    prop3: 3
  },
  {
    prop1: 10,
    prop2: 20,
    prop3: 30
  },
  {
    prop2: 200,
    prop4: 400
  },
  {
    prop3: 3000
  }
];

// to return properties for the following...
const reqProps = ['prop2','prop3','prop4'];

// current implementation fixing return object with prop1, prop3
const obj = data.map(({prop1, prop3}) => {
    return {prop1, prop3};
});

The result of obj for the moment is

[{"prop1":1,"prop3":3},{"prop1":10,"prop3":30},{},{"prop3":3000}]

I do not want to use loops, quite like the 'power' of destructuring! ;)

1
  • What are you trying to do ? use the strings in the array for destructuring ? Commented Sep 5, 2017 at 21:48

2 Answers 2

2

If you insist on destructuring, you have to use eval:

const reqProps = ['prop2','prop3','prop4'];

const literalString = '{'+reqProps.join(',')+'}';

const obj = data.map(new Function(literalString, 'return '+literalString));

You really should use a loop - you can also hide it in a helper function or just use reduce.

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

Comments

2

As @Bergi suggests, you'd better use loops in some way.

Here's a variant with implicit loops:

data.map(o => reqProps.filter(p => p in o)
                      .reduce((acc, p) => ({...acc, [p]: o[p]}), {}))

Comments

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.