How to resolve the algorithm Associative array/Creation step by step in the jq programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Associative array/Creation step by step in the jq programming language
Table of Contents
Problem Statement
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Associative array/Creation step by step in the jq programming language
Source code in the jq programming language
# An empty object:
{}
# Its type:
{} | type
# "object"
# An object literal:
{"a": 97, "b" : 98}
# Programmatic object construction:
reduce ("a", "b", "c", "d") as $c ({}; . + { ($c) : ($c|explode[.0])} )
# {"a":97,"c":99,"b":98,"d":100}
# Same as above:
reduce range (97;101) as $i ({}; . + { ([$i]|implode) : $i })
# Addition of a key/value pair by assignment:
{}["A"] = 65 # in this case, the object being added to is {}
# Alteration of the value of an existing key:
{"A": 65}["A"] = "AA"
def collisionless:
if type == "object" then with_entries(.value = (.value|collisionless))|tostring
elif type == "array" then map(collisionless)|tostring
else (type[0:1] + tostring)
end;
# WARNING: addKey(key;value) will erase any previous value associated with key
def addKey(key;value):
if type == "object" then . + { (key|collisionless): value }
else {} | addKey(key;value)
end;
def getKey(key): .[key|collisionless];
def removeKey(key): delpaths( [ [key|collisionless] ] );
{} | addKey(1;"one") | addKey(2; "two") | removeKey(1) | getKey(2)
"two"
You may also check:How to resolve the algorithm Generic swap step by step in the Visual FoxPro programming language
You may also check:How to resolve the algorithm Determine if a string is numeric step by step in the COBOL programming language
You may also check:How to resolve the algorithm Random number generator (device) step by step in the J programming language
You may also check:How to resolve the algorithm Determine if a string has all unique characters step by step in the 11l programming language
You may also check:How to resolve the algorithm Array concatenation step by step in the Go programming language