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
}
Radex
  • 7,815
  • 23
  • 54
  • 86

3 Answers3

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)
J. Pichardo
  • 3,077
  • 21
  • 37
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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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);
Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38