A cool way to do reflection in javascript

Поделиться
HTML-код
  • Опубликовано: 12 янв 2025

Комментарии • 40

  • @XCanG
    @XCanG 2 месяца назад +29

    Also you have error in your opt function, it should return {[name]: value.value} in your case.

  • @JimmayVV
    @JimmayVV Месяц назад +5

    I feel like a simpler way to solve this problem is to make a function that takes an object, and returns a new object with only the keys on it that are truthy.
    But I like the creativity!

    • @MrREALball
      @MrREALball 19 дней назад

      not truthy, but not undefined (or not null, depending on whats needed)

  • @EmanueleSerini78
    @EmanueleSerini78 2 месяца назад +8

    Nice tip, though this makes me wonder how many people have read a book about javascript

  • @floodlitworld
    @floodlitworld 7 дней назад +1

    I'd go with
    import { toValue } from "vue";
    export const optionalProps = (input) => {
    if (!input || typeof input !== "object") return {};
    const entries = Object.entries(input);
    return entries.reduce((acc, [key, value]) => {
    const resolvedValue = toValue(value);
    if (resolvedValue !== null && resolvedValue !== undefined) {
    acc[key] = resolvedValue;
    }
    return acc;
    }, {});
    };
    That way you can pass in as many optional props as you want and additionally, it will handle any type of value (ref, reactive, computed or primitive).

  • @gustavohenriquejunkes3276
    @gustavohenriquejunkes3276 11 дней назад

    Good video my man, keep it on

  • @nescafezos4265
    @nescafezos4265 7 дней назад

    hmm, I think it need to be `return { [name]: value.value }` (name in a square brackets). because otherwise it will always create a key with name "name" but not the string value in a variable `name`

  • @philadams9254
    @philadams9254 Месяц назад +3

    Just send everything and let the backend logic for favourite colour deal with the empty value - it has to check the value anyway.

  • @wanderingzanzey2126
    @wanderingzanzey2126 2 месяца назад +1

    Love that you're learning and having fun :)
    this video made my brain hurt though ... this is a tutorial on what _not_ to do. Especially using reflection for something that can be solved with a standard. Clever code != Good Code. Bad habits all over the place.

  • @Lk77ful
    @Lk77ful 2 месяца назад +4

    i would always submit all values even when null/undefined

    • @GeneraluStelaru
      @GeneraluStelaru Месяц назад +1

      Careful with sending non-nullable values to a PHP backend.

    • @Lk77ful
      @Lk77ful Месяц назад

      @GeneraluStelaru if it's not nullable, the validation will fail on the php side

  • @rafaelbitencourt6021
    @rafaelbitencourt6021 Месяц назад +3

    ...opt('favoriteColor', favoriteColor)
    function opt(key, ref) { return ref.value ? { [key]: ref.value } : {} }

  • @aminnairidev
    @aminnairidev Месяц назад

    I feel like undefined value should be returned and checked by the API (if the API your are dealing with is correctly setup) not by the client because you are doing work that should be done anyway by the server, so either you are doing twice the work, or the server can be corrupted by a malicious user. Anyway cool to see you are exploring the langage and you had fun!

  • @BehruzbekOtayev
    @BehruzbekOtayev 2 месяца назад +5

    Nice exploration. But over time you come to a realization that simpler is better, especially when you're working in teams. The abstraction you just made is not easily understandable and that might come to bite you in the future. Happens to me sometimes. That doesn't mean you stop doing that. Do it, you're mastering the language.

  • @asagiai4965
    @asagiai4965 Месяц назад

    It's a good thing to learn something new.

  • @joonas175
    @joonas175 Месяц назад

    It's one way of doing this and it's not completely wrong. However, I think you should utilize the undefined value as is instead of this additional logic. JSON.stringify removes undefined values from an object, so just run every object through JSON.stringify before sending to the server. This is the way axios handles for it, for example, and in my opinion it's the correct use case for undefined values. And you kind of need to stringify the request data anyways, since there is no concept of data types in the HTTP layer, it's just bytes being parsed on both ends. In fact, JSON doesn't even contain undefined value, and null should be used to represent an "empty" value. So tl;dr: prefer to use undefined to omit properties, null to represent empty values.

  • @zeenuexe8362
    @zeenuexe8362 Месяц назад

    Huh, I thought this was just normal js object manipulation....

  • @Efim141
    @Efim141 2 месяца назад +1

    Just [r]: r.value wouldn’t work? [r] takes the name of the r variable and it can be used as an object key here

    • @lukasmolcic5143
      @lukasmolcic5143 2 месяца назад +2

      [r] wouldn't be the name of the variable, it would try to take the whole value of r, and use it as the key for the new object

  • @CharlyRipp
    @CharlyRipp 28 дней назад

    Not reflection. Also, the payload must be serialized, if sending via REST - remove null values during serialization.

    • @nescafezos4265
      @nescafezos4265 7 дней назад

      I thought JSON serializing (if that's what happens) removes `undefined` values but keeps null

    • @CharlyRipp
      @CharlyRipp 2 дня назад

      Yup, but you can supply a transformer function to drop nulls along the way as well. Might as well do it all in the single loop of serialization.

  • @ssahillppatell
    @ssahillppatell 23 дня назад

    damn nice. thanks

  • @sandervspl
    @sandervspl Месяц назад +4

    Its called “spread operator” not “rest operator” 😄 sorry it started to annoy me a bit after you said it multiple times haha

  • @Cdaprod
    @Cdaprod Месяц назад

    Nice [[]]

  • @alifrahman7099
    @alifrahman7099 2 месяца назад

    cool

  • @komatikvengeance8811
    @komatikvengeance8811 28 дней назад +1

    You could have solved it with something like ...(favcolor.value && { favcolor: favcolor.value } its shorter than what you had and easier to reason with than what you later developed. But yes its a nice discovery you made regarding reflection.

    • @NOPE96
      @NOPE96 8 дней назад +1

      That is only applicable if you're only having one value named favcolor. If it's multiple one's his approach is sure valid.

  • @ZSpecZA
    @ZSpecZA 2 месяца назад

    You can do it more simply with
    function submit() {
    const payload = Object.fromEntries(
    Object.entries({ name, email, favoriteColor })
    .filter(([_, ref]) => ref?.value != null)
    .map(([key, ref]) => [key, ref.value])
    );
    post(payload);
    }
    Some of the utility libraries like Lodash/Underscore.js also give you access to a `mapValues` type utility function that does the same as above, but more efficiently and less code on your part. `zip`/`unzip` are also functions in these utility libraries that help a lot with this kind of object transformation and go tegether well with `fromEntries` / `toEntries`.

    • @AkioJunichiro
      @AkioJunichiro 2 месяца назад +1

      4 loops under the hood tho
      - fromEntries
      - entries
      - filter
      -map
      his the solution 2 loops
      -entries
      -spread operator

    • @ZSpecZA
      @ZSpecZA 2 месяца назад

      @@AkioJunichiro Which is why I mentioned utility libraries. In this example however, the number of loops doesn't matter. If it were a bigger object, then sure, but for something with

  • @royz_1
    @royz_1 Месяц назад

    I was so invested in this video only to discover the most basic and commonly used pattern for creating objects.
    No hate though, I liked the way you explained. It would help out beginners I guess.
    If you watch any beginner level tutorial about javascript objects, you will find this pattern being explained.

  • @DaxSudo
    @DaxSudo Месяц назад

    Like 100