Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

330
Views
How use JQ to merge array into array of objects

I want to see if jq with js can help me to achieve the following:

I have the following object:

[
  {
    "a": 1,
    "b": 2
  },
  {
    "a": 11,
    "b": 12
  },
  {
    "a": 21,
    "b": 22
  }
]

and the following array:

[3,13,33,44]

I want to add the array items to the object according to their order as an extra field, it should also work when array is longer/shorter than the array of objects.

the result should look like this:

[
  {
    "a": 1,
    "b": 2,
    "c": 3
  },
  {
    "a": 11,
    "b": 12,
    "c": 13
  },
  {
    "a": 21,
    "b": 22,
    "c": 33
  }
]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Let's assume that you are interested in a jq solution, that the array of objects is in a file objects.json, and that you are willing to invoke jq along the following lines:

jq --argjson c '[3,13,33,44]' -f program.jq objects.json

Let's also assume for now that the result should NOT be lossy i.e., that the length of the resulting array should be the greater of the two input array lengths.

Then the following jq program will be of interest:

< objects.json jq --argjson c '[3,13,33,44]' '
  ({$c}|keys[0]) as $k
  | [., ($c | map ( {($k): .} ))]
  | transpose
  | map(add)
'

Notice how the key name ("c") is derived from the parameter name on the command line.

There are various ways to trim the result so it has the length of the shorter of the two arrays, and it seems reasonable to leave that as an exercise.

about 4 years ago · Juan Pablo Isaza Report

0

Using to_entries :

jq --argjson c '[4,13,33,44]'\
   'to_entries|
    map(
        .value + (if .key<($c|length) then {c:$c[.key]} else {} end)
       )' objects.json
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!