0

If I have something like,

const {
  someProperty,
  anotherProperty,
  thirdProperty
} = someObject;

const includeProperties = ['someProperty', 'thirdProperty']

Is it possible to make anotherProperty = null?

5
  • 1
    Don't make it const, then you can set Commented Feb 19, 2020 at 11:24
  • 1
    I want to destructure first, and then conditional set a value to null if it doesn't exist in includeProperties Commented Feb 19, 2020 at 11:30
  • const { someProperty, anotherProperty, thirdProperty } = someObject; By this, you are trying to declare those variables right? Commented Feb 19, 2020 at 11:35
  • 1
    Yes, first declare and then nullify if needed. Commented Feb 19, 2020 at 11:36
  • Have you solved your problem or still looking for some better options? Commented Feb 20, 2020 at 13:33

3 Answers 3

2

You may nullify all the not needed properties within source object shallow copy and destructure that:

const srcObj = {a:1, b:2, c:3},
      neededKeys = ['a','b'],
      objCopy = (obj =>
        (Object.keys(obj).forEach(key =>
          !neededKeys.includes(key) && (obj[key]=null)), obj)
      )({...srcObj}),
      {a,b,c} = objCopy
      
console.log(a,b,c)
.as-console-wrapper{min-height:100%;}

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

2 Comments

This does not answer the question. Property c in obj would exist in the case of the question.
@MikeK : considering your use case, that would be easier to nullify unwanted props before destructuring
1

You can use Array.prototype.reduce

let properties = [
  'someProperty',
  'anotherProperty',
  'thirdProperty'
]

const includeProperties = ['someProperty', 'thirdProperty'];

let object = properties.reduce((acc, val) => {

  if (includeProperties.indexOf(val) === -1) 
    acc[val] = null;
  else 
    acc[val] = 'some value';
  
  return acc;
}, {});

console.log(object);

Comments

0
    let someProperty = someObject,
       anotherProperty = someObject,
       thirdProperty = someObject;

    const includeProperties = [someProperty, thirdProperty];

if (!includeProperties.include(someVariable))
    someVariable= null;
}

This is a possible way to do what you asked.

3 Comments

Is this what you expected?
But this is not dynamic in any way. I might not know the properties to nullify.
Do you want to nullify the variable if it is not in array?

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.