Something like a for loop to avoid repetition

Is it possible to iterate/feed a list or attribute set of lists to a nixos configuration file.

Something like this:

[ 
  { "name" = "foo"; "id" = "1" } 
  { "name" = "moo"; "id" = "2" } 
];

to

"${name}" = {
    "attrib" = {
      "name" ="${name}";
      "uid" = "${id}";
     };
};

like in a for loop, in any other language.

Nix by example - NixOS Wiki suggests you can loop via recursion, but not with something like a for loop.

1 Like

I am very new to nix language, learning.

I already saw that, but couldn’t get my head around how to apply it to my example.

from your example it looks like you’re looking for a combination of map and listToAttrs. have a look at the builtins and the library reference in the nixpkgs manual, there’s a whole lot of functionality in there that makes explicit looping mostly unnecessary.

3 Likes
nix repl > let x = [ { name = "foo"; id = "1"; } { name = "moo"; id = "2"; } ]; in builtins.listToAttrs (map ({ name, id }: lib.nameValuePair name { attrib = { inherit name 
id; }; }) x)
{ foo = { attrib = { id = "1"; name = "foo"; }; }; moo = { attrib = { id = "2"; name = "moo"; }; }; }
2 Likes

There are map/fold/filter functions and such in Built-in Functions - Nix Reference Manual and some more utility functions building up from here in nixpkgs.

1 Like

Theres also nixpkgs.lib.genAttrs. if you want to set a name though, you have to write your own function

3 Likes