Tomáš Vavřinka
Tomáš Vavřinka

Reputation: 633

How to get the nth value and key of a Sass list?

How to get nth item (value, key) of list in SASS?

Let's say that exists following list:

$list: ( 
  'foo1': 11,
  'foo2': 22,
  'foo3': 33
);

I want to get for example 2nd item to have:

$2nd-key: 'foo2';
$2nd-value: 22;

Upvotes: 1

Views: 2028

Answers (1)

ReSedano
ReSedano

Reputation: 5060

That is not a list, it's a map. So you can use map functions to extract a value or a key. There are many interesting functions and work very well with loops.

To answer your question, you could use for example 2 of these functions (map-keys() & map-values()) to create a list of keys and values from your map and than use the nth() function to get your desired value or key:

$map: ( 
  'foo1': 11,
  'foo2': 22,
  'foo3': 33
);

div{
  content:nth(map-keys($map), 2);
  z-index:nth(map-values($map), 2);
}

The output:

div {
  content: "foo2";
  z-index: 22;
}

nth() tells Sass to step through each value of the map. Otherwise, you'd just assign the first value of the map, 11, to each variable in your list (if there were multiple variables).

Upvotes: 5

Related Questions