8
$\begingroup$

JSON often returns sort of 'nested' associations like so:

assoc = <|"key1" -> <|"a" -> 1, "b" -> 2|>, 
          "key2" -> <|"a" -> 3, "b" -> 4|>|>

It is often needed to apply f as follows.

assoc = <|"key1" -> <|"a" -> f[1], "b" -> 2|>, 
          "key2" -> <|"a" -> f[3], "b" -> 4|>|>

I see some traditional ways, i.e. MapAt, but I'm searching more specific way for the task, like KeyValueMap or something similar. Which one would you recommend? (Parsing APIs results is a good example of usecase.)

$\endgroup$
0

2 Answers 2

13
$\begingroup$

I have failed to find a good duplicate so:

assoc // Query[All, {"a" -> f}]

or

MapAt[f, assoc, {All, "a"}]
$\endgroup$
7
$\begingroup$
assoc = <|"key1" -> <|"a" -> 1, "b" -> 2|>, "key2" -> <|"a" -> 3, "b" -> 4|>|>;
assoc[[All, "a"]] = Map[f, Values[assoc[[All, "a"]]]];
assoc

<|"key1" -> <|"a" -> f[1], "b" -> 2|>, "key2" -> <|"a" -> f[3], "b" -> 4|>|>

$\endgroup$
1
  • 1
    $\begingroup$ Kuba's solution is much shorter (+1) but an in-place modifcation may also have its applications. $\endgroup$ Commented Jan 15, 2018 at 11:37

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.