Modify arrays within objects in jq

Paul Draper

I have an array of objects, and want to filter the arrays in the b property to only have elements matching the a property of the object.

[
  {
    "a": 3,
    "b": [
      1,
      2,
      3
    ]
  },
  {
    "a": 5,
    "b": [
      3,
      5,
      4,
      3,
      5
    ]
  }
]

produces

[
  {
    "a": 3,
    "b": [
      3
    ]
  },
  {
    "a": 5,
    "b": [
      5,
      5
    ]
  }
]

Currently, I've arrived at

[.[] | (.a as $a | .b |= [.[] | select(. == $a)])]

That works, but I'm wondering if there's a better (shorter, more readable) way.

oguz ismail

I can think of two ways to do this with less code and both are variants of what you have already figured out on your own.

  1.  map(.a as $a | .b |= map(select(. == $a)))
    
  2.  del(.[] | .a as $a | .b[] | select(. != $a))
    

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

jq — Extract strings contained in nested arrays and objects

Delete objects and arrays with jq which match a key

Convert Json table arrays to objects with jq

Explode Complex JSON Object (with Objects and Arrays) with jq

how to extract and modify inner array objects with parent object data in jq

Getting access to deep nested arrays within objects

How to Filter objects and arrays within Javascript Array

getting specific values from objects within arrays

jq - remove duplicate entries within all arrays inside the JSON file

Accessing nested JSON objects and arrays within objects to display in HTML - AngularJS

Loop through array of objects, and combine arrays within objects

Map over two arrays with jq and merge objects inside

Convert json single-item arrays to objects using bash/jq

How to merge different objects and arrays in the same json file using jq

JQ get unique objects and arrays based on key value

Transforming arrays of varying length into objects based on the parity of their indices in JQ

Modify objects in resutl array when combining two arrays into one

How to modify array of object arrays into a single array of objects?

I am having trouble accessing nested objects within arrays within objects

Parsing JSON Objects within JSON arrays within JSON Objects in VB.Net

How to merge with jq json arrays elements where elements are objects with nested arrays?

Angular ng-repeat get objects within arrays?

How to get array of unique values from arrays within an array of objects?

Get the total count / length of arrays within objects ES6

When to use arrays within JavaScript objects (or mix them)?

create a matrix of objects with x y coordinates within arrays in vanilla JavaScript

How to get a the sum of multiple arrays within an array of objects?

Finding the comma, where is it coming from? Javascript Arrays within Objects

How can I work with arrays and json objects within the laravel framework?