<p>When I use &quot;kubectl patch&quot; to delete a specific object in an array, I need to first check the index of that specific object, and then do the kubectl patch with the json/yaml path.</p>
<p>For example, I have an resource contains multiple port object:</p>
<pre><code>spec:
  clusterIP: 100.12.143.76
  externalTrafficPolicy: Cluster
  ports:
  - name: object1
    nodePort: 30681
    port: 1234
    protocol: TCP
    targetPort: 1234
  - name: object2
    nodePort: 31805
    port: 9876
    protocol: TCP
    targetPort: 9876
</code></pre>
<p>If I need to remove the &quot;object1&quot; in the ports, here is the command I am using now (kong-proxy is the name of this service resource):</p>
<pre><code>kubectl patch service kong-proxy --type=json -p='[{&quot;op&quot;: &quot;remove&quot;, &quot;path&quot;: &quot;/spec/ports/0&quot;}]' -n kong
</code></pre>
<p>By doing the command above, it deletes the object at index &quot;0&quot; which with the name &quot;object1&quot;.</p>
<p>But this requires the person to know the correct index number in advance, and if there are too many objects in an array, it will be hard to manage and calculate the index.</p>
<p>Therefore I wonder without writing a separate bash script, is there a way that I can delete the object with an identifier in it.</p>
<p>Such as:</p>
<pre><code>kubectl patch service kong-proxy --type=json -p='[{&quot;op&quot;: &quot;remove&quot;, &quot;path&quot;: &quot;/spec/ports/{name:object1}&quot;}]' -n kong
</code></pre>

JackHuang-RoboMQ
<p>I'm afraid it's not possible. The <code>kubectl patch --type=json</code> command uses <a href="https://www.rfc-editor.org/rfc/rfc6902" rel="noreferrer">JSON Patch</a> under the hood, which in turn uses <a href="https://www.rfc-editor.org/rfc/rfc6901" rel="noreferrer">JSON Pointer</a>. JSON Pointer standard is pretty simple and does not provide filtering/matching functionality.</p>
<p>What you could do as a work around is using <a href="https://stedolan.github.io/jq/" rel="noreferrer">jq</a> to find the array index, before calling <code>kubectl patch</code>:</p>
<pre class="lang-sh prettyprint-override"><code>INDEX=$(kubectl get svc kong-proxy -n kong -o json  | jq '.spec.ports | map(.name == &quot;object1&quot;) | index(true)')

kubectl patch svc kong-proxy --type=json -p=&quot;[{'op': 'remove', 'path': '/spec/ports/$INDEX'}]&quot; -n kong
</code></pre>
