0

I need to create a function which create a new object with all properties of in set to true, the function should create a new object.

How to do it with vanilla js? I can use deconstruction and latest JS.

 const in = { ida:true, idb:false, idc:false, ide:true } 

result wanted

const out = { ida:true, idb:true, idc:true, ide:true } 
7
  • I have tried with reduce but no result.. :( Commented Jun 5, 2018 at 14:40
  • Please publish, what you try Commented Jun 5, 2018 at 14:40
  • Possible duplicate of Set all Object keys to false Commented Jun 5, 2018 at 14:41
  • 3
    Possible duplicate of Iterate through object properties Commented Jun 5, 2018 at 14:41
  • "How to do it with vanilla js?" — Use an immutable library. Don't reinvent the wheel. Commented Jun 5, 2018 at 14:42

3 Answers 3

4

Well, you could use Object.keys and the spread operator to accomplish this:

const input = { ida: true, idb: false, idc: false, ide: true } const out = Object.keys(input).reduce((acc, key) => ({...acc, [key]: true}), {}); console.log(out)

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

Comments

2

You could map all keys with an new object and false as value. Later assign them to a single object.

const inO = { ida: true, idb: false, idc: false, ide: true }, outO = Object.assign(...Object.keys(inO).map(k => ({ [k]: true }))); console.log(outO);

8 Comments

thanks, but I this warning Expected at least 1 arguments but got 0 or more any idea?
I am using typescript
With destructuring I find it more elegant to use { ...Object.keys } instead of Object.assign
@Logar that's the same as my answer :)
@J.Pichardo ah yeah, just noticed :)
|
0

You can use a for..in loop which iterates over the keys of an object:

function setTrue(obj) { for (k in obj) obj[k] = true; } const o = { ida: true, idb: false, idc: false, ide: true } setTrue(o); console.log(o);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.