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

1

6

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?

Amoebaean answered 11/6, 2016 at 12:15 Comment(5)
try map-keys() ?Ap
It still does not show me how to get the $key name instead of value. I am looking at here: map-keys(("foo": 1, "bar": 2)) => "foo", "bar"Amoebaean
map-keys() will return key strings. What does "$key name" mean? Do you mean you want to get the variable name's string?Ap
Just like above. I want to be able to retrieve "age" and "sex" with or without their values.Amoebaean
I have answer it below. do you mean like that?Ap
A
14

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}";
        }

    }

}
Ap answered 13/6, 2016 at 14:37 Comment(2)
Hey thanks that worked, I did not realise you could add them up in this fashion. I am on my phone but I take it that there is a way of making this more dynamic i.e. i.e. @mixin person-details($person-name, $key);Amoebaean
This answer could benefit from an explanation.Foresee

© 2022 - 2024 — McMap. All rights reserved.