A cool way to do reflection in javascript

แชร์
ฝัง
  • เผยแพร่เมื่อ 1 ก.พ. 2025

ความคิดเห็น •

  • @XCanG
    @XCanG 3 หลายเดือนก่อน +32

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

    • @wilkesreid
      @wilkesreid 3 หลายเดือนก่อน

      You are correct

  • @EmanueleSerini78
    @EmanueleSerini78 3 หลายเดือนก่อน +9

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

  • @JimmayVV
    @JimmayVV 2 หลายเดือนก่อน +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 หลายเดือนก่อน

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

  • @gamenation9706
    @gamenation9706 13 วันที่ผ่านมา

    I normally pass everything and let the backend do its thing

  • @gustavohenriquejunkes3276
    @gustavohenriquejunkes3276 หลายเดือนก่อน

    Good video my man, keep it on

  • @rafaelbitencourt6021
    @rafaelbitencourt6021 หลายเดือนก่อน +4

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

  • @wanderingzanzey2126
    @wanderingzanzey2126 3 หลายเดือนก่อน +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 3 หลายเดือนก่อน +4

    i would always submit all values even when null/undefined

    • @GeneraluStelaru
      @GeneraluStelaru 2 หลายเดือนก่อน +1

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

    • @Lk77ful
      @Lk77ful 2 หลายเดือนก่อน

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

  • @floodlitworld
    @floodlitworld 27 วันที่ผ่านมา +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).

  • @nescafezos4265
    @nescafezos4265 28 วันที่ผ่านมา

    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`

  • @asagiai4965
    @asagiai4965 2 หลายเดือนก่อน

    It's a good thing to learn something new.

  • @Cdaprod
    @Cdaprod หลายเดือนก่อน

    Nice [[]]

  • @ssahillppatell
    @ssahillppatell หลายเดือนก่อน

    damn nice. thanks

  • @BehruzbekOtayev
    @BehruzbekOtayev 3 หลายเดือนก่อน +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.

    • @EmanueleSerini78
      @EmanueleSerini78 3 หลายเดือนก่อน

      Teams should RTFM i guess

  • @aminnairidev
    @aminnairidev 2 หลายเดือนก่อน

    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!

  • @alifrahman7099
    @alifrahman7099 3 หลายเดือนก่อน

    cool

  • @CharlyRipp
    @CharlyRipp หลายเดือนก่อน

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

    • @nescafezos4265
      @nescafezos4265 28 วันที่ผ่านมา

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

    • @CharlyRipp
      @CharlyRipp 23 วันที่ผ่านมา

      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.

  • @philadams9254
    @philadams9254 หลายเดือนก่อน +4

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

  • @joonas175
    @joonas175 2 หลายเดือนก่อน

    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.

  • @Efim141
    @Efim141 3 หลายเดือนก่อน +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 3 หลายเดือนก่อน +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

  • @zeenuexe8362
    @zeenuexe8362 หลายเดือนก่อน

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

  • @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

  • @111ramico
    @111ramico 10 วันที่ผ่านมา

    you should
    return {
    [name]:value.value
    } // or it wont work

  • @DaxSudo
    @DaxSudo หลายเดือนก่อน

    Like 100

  • @komatikvengeance8811
    @komatikvengeance8811 หลายเดือนก่อน +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 29 วันที่ผ่านมา +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 3 หลายเดือนก่อน

    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 3 หลายเดือนก่อน +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.