0

Say I have a JSON,

{
"x" : 1,
"y" : 2
}

My need here is to add a value, if y is 2 set the value for y as 2 in JSON or else set as 3.

Note: I have to make this operation inside JSON itself. Do we have any logical or ternary operators that can be used inside JSON?

Deepak raj
  • 49
  • 1
  • 10
  • I think you're confused between javascript object and JSON, here's the spec for JSON document (https://www.json.org/json-en.html). JSON doesn't have logical operator – ThatBuffDude May 13 '20 at 07:39
  • JSON is a completely static text serialisation format, so no. If you mean a JavaScript object which *is* actual code, then you can use any expression you wish during initialisation but [you cannot self-reference during initialisation](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers) – VLAZ May 13 '20 at 20:26

1 Answers1

0

You can use ternary operation to assign the value here. Please find the below example to achieve what you are looking for.

let y = 2;

const getObj = (y) => ({
   "x" : 1,
   "y" : y === 2 ? y: 3
})

console.log(getObj(y));

y = 4;

console.log(getObj(y));
Nithish
  • 5,393
  • 2
  • 9
  • 24