How can I use the key name instead of value in map-get?

HGB picture HGB · Jun 11, 2016 · Viewed 10.3k times · Source

I am trying to create a function that simply enables me to output the key name and key value of a simple two-dimensional map in CSS:

$people: (
    "Hellen": (
        age: "34",
        sex: "female"
    ),
    "Patrick": (
        age: "23",
        sex: "male"
    ),
    "George": (
        age: "10",
        sex: "male"
    ),
    "Vicky": (
        age: "19",
        sex: "female"
    )
);

I am creating a simple function to retrieve this information:

@each $person-name, $person-details in $people {
    $age: map-get($person-details, 'age');
    $sex: map-get($person-details, 'sex');

    .#{$person-name} {

        height: 100 px;
        width: 100 px;
        background: #FF3C00;
        margin: 0 auto;

        &:before {
            content:$person-name " " + $age " ";
        }

        &:after {
            content: $sex;
        }

    }

}

HTML:

<div class="Hellen"></div>

But I can't find any information that will out both the key and value as separate objects. I can only read the value, not the key with the following:

$age: map-get($person-details, 'age');

result:

Hellen 34 female

instead of: Hellen age:34 sex:female

How can I get the key label with or without the value?

Answer

twxia picture twxia · Jun 13, 2016

use map-keys() to get all keys in the list.

Sample:

@each $person-name, $person-details in $people {
    $age: map-get($person-details, 'age');
    $sex: map-get($person-details, 'sex');
    $keys: map-keys($person-details);

    .#{$person-name} {

        height: 100 px;
        width: 100 px;
        background: #FF3C00;
        margin: 0 auto;

        &:before {
            content:"#{$person-name}  #{nth($keys, 1)} : #{$age} ";
        }

        &:after {
            content: "#{nth($keys, 2)}: #{$sex}";
        }

    }

}