0

I need to change a nested variable property. First check if it exists then change it to 'N/A' if necessary. This is what I have.

const json = {
 isCat: {
    isAvaliable: true,
    count: 5
  },
  isDog: {
    isAvaliable: true,
    count: 10
  },
  isFrog: {
    isAvaliable: false,
    count: null
  }
}

const newJson = { ...json }
if(!jsonObj.isCat.count) {
    newJson = {...newJson, json.isCat.count: 'N/A'}
}

Im not sure how to set count lets say by goign directly to it and changing the value. It seems simple maybe im missing something.

I can see the value in the if statement but i cant make any changes to the actual property value itself. Basically if a value is null, change it to 'N/A'

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
chrus54321
  • 125
  • 7

3 Answers3

1

You can use array reduce method. First get all the keys using Object.keys method. Then traverse the keys and check the count is null or not. If null then change it to 'N/A'.

const json = {
  isCat: {
    isAvaliable: true,
    count: 5,
  },
  isDog: {
    isAvaliable: true,
    count: 10,
  },
  isFrog: {
    isAvaliable: false,
    count: null,
  },
};

const ret = Object.keys(json).reduce((prev, c) => {
  const p = prev;
  if (!json[c].count) p[c] = { ...json[c], count: 'N/A' };
  else p[c] = { ...json[c] };
  return p;
}, {});
console.log(ret);
mr hr
  • 3,162
  • 2
  • 9
  • 19
1

Using Object.entries and Object.fromEntries you can map the old object to the new object. If the count property is truthy, i.e. not null then map it through, otherwise shallow copy the element and update the count property with the new "N/A" value. This avoids mutating your original object.

const newJson = Object.fromEntries(Object.entries(json).map(([key, value]) => ([
  key,
  value.count ? value : { ...value,
    count: 'N/A'
  }
])));

const json = {
  isCat: {
    isAvaliable: true,
    count: 5
  },
  isDog: {
    isAvaliable: true,
    count: 10
  },
  isFrog: {
    isAvaliable: false,
    count: null
  }
};

const newJson = Object.fromEntries(Object.entries(json).map(([key, value]) => ([
  key,
  value.count ? value : { ...value,
    count: 'N/A'
  }
])));

console.log(newJson);
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
1

Another solution with reduce. Beware of it's comma operator in the return value.

const json = {isCat: {isAvaliable: true,count: 5,},isDog: {isAvaliable:true,count: 10,},isFrog: {isAvaliable: false,count: null,},};

const res = Object.keys(json).reduce((pV,cV)=>(json[cV].count==null?json[cV].count='N/A':null,json),{});
console.log(res);
MWO
  • 2,627
  • 2
  • 10
  • 25
  • What if isCat doesnt exist and I still want to set isAvailable to false for example – chrus54321 Oct 27 '20 at 20:10
  • then it would be better to use Object.entries() instead of Object.key() where you can check for the current key name == isCat – MWO Oct 27 '20 at 20:25