0

I would like to ask for help. How can I transfer array to one list. My input is

[
  {
    "PartNumber": "5SD30104GN114",
    "ClassificationNo": "500001",
    "StringValue": "L0035WSGE",
    "Field": "95001"
  },
  {
    "PartNumber": "5SD30104GN114",
    "ClassificationNo": "500001",
    "StringValue": "",
    "Field": "95002"
  }
]

And I like to expect this

[
  {
    "PartNumber": "5SD30104GN114",
    "ClassificationNo": "500001",
    "95001": "L0035WSGE",
    "95002": "",
  }
]

How Can I do ? I tried use

| .[] | [.PartNumber, .ClassificationNo, .StringValue, .Field]

But generate again arrays

[
  "5SD30104GN114",
  "500001",
  "L0035WSGE",
  "95001"
]
[
  "5SD30104GN114",
  "500001",
  "",
  "95002"
]

2 Answers 2

1

Here's a solution using reduce:

group_by({PartNumber,ClassificationNo})
| map(reduce .[] as $item ({}; .+($item|{PartNumber, ClassificationNo, (.Field):.StringValue})))

Probably not the most efficient one (part number and classification number are always overwritten), but it gets the job done while being somewhat readable.

Output:

[
  {
    "PartNumber": "5SD30104GN114",
    "ClassificationNo": "500001",
    "95001": "L0035WSGE",
    "95002": ""
  }
]

With a function:

def reducer($item):
  $item|{PartNumber, ClassificationNo, (.Field):.StringValue};

group_by({PartNumber,ClassificationNo})
| map(reduce .[] as $item ({}; .+reducer($item)))
Sign up to request clarification or add additional context in comments.

Comments

1

You can use group_by to make clusters of matching IDs (I assumed .PartNumber together with .ClassificationNo to make a unique ID), then within each cluster, take the ID fields from the first item (all have the same ID fields), and add to it the values of all items by converting them to a key-value structure that can be used with from_entries to turn it into an object:

group_by([.PartNumber, .ClassificationNo]) | map(
  (first | {PartNumber, ClassificationNo}) +
  (map({key: .Field, value: .StringValue}) | from_entries)
)

Demo

Instead of from_entries, you can also use INDEX to create an object with the right fields, but then subsequently the values need to be trimmed down to only contain the right values:

group_by([.PartNumber, .ClassificationNo]) | map(
  (first | {PartNumber, ClassificationNo}) +
  (INDEX(.Field) | .[] |= .StringValue)
)

Demo

[
  {
    "PartNumber": "5SD30104GN114",
    "ClassificationNo": "500001",
    "95001": "L0035WSGE",
    "95002": ""
  }
]

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.