Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add calculated value from an array field to the same array

Not sure if it is possible. I want multiply the "value" field with the "lvalue" field an put the result in a new field "calc" in the corresponding array entry.

Given JSON:

{
  "value": 5,
  "location": [{
    "city": "San Fracisco",
    "lvalue": 10
  },
  {
    "city": "Los Angeles",
    "lvalue": 20
  }]
}

Expected Value in one JSON:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "value": 5,
  "location": [{
    "city": "San Fracisco",
    "lvalue": 10,
    "calc": 50
  },
  {
    "city": "Los Angeles",
    "lvalue": 20,
    "calc": 100
  }]
}

>Solution :

You need to ‘save’ the .value in a variable before looping over the locations to update them using |=:

.value as $val | .location[] |= (.calc = $val * .lvalue)

JqPlay Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading