4

Please note that this post is tagged jq, I am not trying to do this with javascript at all.

I have an object that has an array as one of its fields. I'd like to remove the elements from the object's array that match a criteria, but keep the object around. I've looked around and I've only been able to spot snippets of returning just the array that happens to have less items now.

Here's an example:

{
  "foo": "bar",
  "events": [
    {
      "id": 1,
      "msg": "starting"
    },
    {
      "id": 2,
      "msg": "working on it"
    },
    {
      "id": null,
      "msg": "done"
    }
  ]
}

and I'd like to get back the following:

{
  "foo": "bar",
  "events": [
    {
      "id": 1,
      "msg": "starting"
    },
    {
      "id": 2,
      "msg": "working on it"
    }
  ]
}

Note: Just in case this will affect the answer I'm really only interested in the last element. I plan to build up a new object in a following pipe stage like:

jq '$answer | {bar:.foo, event: .events[-1].msg}`

I have tried both

select(.events[].id != null)

and

del(.events[], select(.id == null)))

with no luck.

5
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented May 25, 2018 at 16:14
  • Thanks @nurdyguy but I'm looking for jq syntax. Commented May 25, 2018 at 16:20
  • It's not an ideal solution but it is about as good as it gets for this situation. Commented May 25, 2018 at 16:23
  • I'm talking about jq the json query tool, not jQuery. Commented May 25, 2018 at 16:42
  • Sorry, the JSON format threw me. I've removed my answer. Commented May 25, 2018 at 16:45

2 Answers 2

6

I think you are probably looking for jq filter as below. The expression .events[] | select(.id == null) returns the key to the object where the id value is null and del() deletes that key/value pair.

jq 'del(.events[] | select(.id == null))'

As a side note, if you just want to delete an element just by index, you could just use as below. The example below deletes the element from index 2, the array actually starts at 0.

jq 'del( .events[2] )'

But remember this way is not recommended for your original problem, since you wouldn't know which index of your key would contain the null value.

Sign up to request clarification or add additional context in comments.

Comments

0

When in doubt (sometimes del(...) is a bit tricky), you can always use map(select(...)), e.g. in the present case:

.events |= map(select(.id != null))

or perhaps even:

.events |= map(select(.id))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.