Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

LifeLynx posted:

Alright, here it is: https://codepen.io/LyfeLynx/pen/ExgdmoM

It seems to work well. The only problem I have is that the order keeps going up and up. It assigns every item an order number at the start, and keeps incrementing the flex order by 1 every two seconds. The easiest thing I can think of is to periodically reset it by fading the carousel out, say if the flex order reaches 3000 because no one's looking at this for six minutes, doing the prepareCarousel, and then fading back in.

Not necessarily your problem, but if you want to increment a loop that circles back on itself:

code:
const NUM_ITEMS = 8; // number of things in your loop
// obviously you'd use "someArrayOfItems.length" instead most likely, but anyway...

const incrementIndex = (currentIndex) => ++currentIndex % NUM_ITEMS;

Adbot
ADBOT LOVES YOU

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?

LifeLynx posted:

Newer code:

Looks a lot better. Just one more comment:
code:
		carItems.forEach(function(carItem) {
			carItem.width = carWidth/numSlides;
			carIndex = 0;
			currentTarget = 0;
			carItem.style.order = carIndex;
			carItem.style.marginLeft = 0;
			carItem.style.opacity = 0.5;
		});
There's no need to be setting carIndex and currentTarget in this loop. Also all items start with the same order (0). This doesn't really affect much because items with the same order show up in the order they're specified in the HTML.

One more thing: you should always use "use strict"; IMO

Edit: Oh, on the order thing

LifeLynx posted:

It seems to work well. The only problem I have is that the order keeps going up and up. It assigns every item an order number at the start, and keeps incrementing the flex order by 1 every two seconds. The easiest thing I can think of is to periodically reset it by fading the carousel out, say if the flex order reaches 3000 because no one's looking at this for six minutes, doing the prepareCarousel, and then fading back in.

I guess what you want is for the current item to have the largest index. You can do that like this (replacing theCarousel.children[currentTarget].style.order = carIndex;):
code:
    for (var i = 1; i <= carItems.length; i++) {
      var itemIdx = (i + currentTarget) % carItems.length;
      theCarousel.children[itemIdx].style.order = i;
    }
Using % causes the itemIdx to loop around, always staying in the range [0, carItems.length). The loop starts with the item right after currentTarget and assigns it the lowest order, continuing until it wraps around to currentTarget, which it assigns the largest order

HappyHippo fucked around with this message at 20:17 on Jan 14, 2021

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Is there anyway to pass a variable from a .try to a .catch? Should I even do that?

Basically in Expressjs I'm running a pg-promise call, but I want the error to call the data returned from the pg call, if that makes sense. here's my code:

code:
 db.tx(async (t) => {
      const companys = await t.any("SELECT company_name, id FROM company");
      const insertion = await t.none(
        "INSERT INTO useraccount(username, password,email, company_id) VALUES ($1, $2, $3, $4)",
        [req.body.username, hash, req.body.email, req.body.companyradio]
      );

      return companys;
    })
      .then((data) => {
        console.log(data);
        res.redirect("/");
      })
      .catch((err) => {
        if (err) {
          res.render("signup", {
            title: "Sign Up",
            companys: WHAT DO I PUT HERE,
            error: err,
            user: req.user,
          });
        }
      });
so in that .catch res.render I'm trying to pass the companies result from company variable back into the new render. I'm sure there's a overall better way to do this though if anyone has a suggestion.

necrotic
Aug 2, 2005
I owe my brother big time for this!
Put a let someVar before the promise starts and then reassign it as needed.

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
sweet thanks

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
is there anyway to access the Dom and do javascript css manipulation with Express/Node?

Like say I want to have a conditional on a form, if you check this box open up these two fields from display:none to whatever?

I think I might be hitting a point in my project where PUG needs to be replaced with a full on front end system?

Thanks!

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Empress Brosephine posted:

is there anyway to access the Dom and do javascript css manipulation with Express/Node?

Like say I want to have a conditional on a form, if you check this box open up these two fields from display:none to whatever?

I think I might be hitting a point in my project where PUG needs to be replaced with a full on front end system?

Thanks!

If the user is interacting with the page, it is out of express’ hands. You want to use the original intent of JS, running in the browser. :v:

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Yeah that's a bummer but not unexpected. Thanks!

Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer

Empress Brosephine posted:

is there anyway to access the Dom and do javascript css manipulation with Express/Node?

Like say I want to have a conditional on a form, if you check this box open up these two fields from display:none to whatever?

I think I might be hitting a point in my project where PUG needs to be replaced with a full on front end system?

Thanks!

That's frontend js stuff, unless you do all your rendering server side in which case you'd send the state of the page back to the server for every action and get fresh html. Probably more complicated for a small use case than just having some frontend js

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
If all I want to do is a conditional form id be better just doing a small frontend script then installing something like react or vue right?

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Empress Brosephine posted:

If all I want to do is a conditional form id be better just doing a small frontend script then installing something like react or vue right?

tbh something like that is pretty solidly in the react wheelhouse. if it were ten years ago I would say do vanilla js, but there are actually enough ways to gently caress up conditional forms in vanilla js (wrt input sanitization) that you might actually want to use react for this.

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
I'll do that then probably. I need to make a simple search page for accessing a database so the extra functionality might not hurt. Or maybe it'll be time to check out Svelte.

Thanks everyone.

Roadie
Jun 30, 2013

Empress Brosephine posted:

I'll do that then probably. I need to make a simple search page for accessing a database so the extra functionality might not hurt. Or maybe it'll be time to check out Svelte.

Thanks everyone.

If you've already got an Express backend, you may want to look at using Next.js, which lets you get a working React frontend right out of the box (no need to gently caress around with Webpack, etc) and includes Express-like server functionality so you can do everything with a single dev server.

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Ill probably do that; I guess most people when using react just use express as a API generator and work off of that?

The Fool
Oct 16, 2003


My last project queried Azure Functions, but otherwise, yes.

It doesn’t really matter what you use as your backend. Django Rest Framework is popular too.

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
yeah, I think my broke brain just loves express and I don't know why. Nothing else clicks except for this, but I also enjoy doing CRUD operations a lot too. I think I have a future in mediocrity but that's a-ok with me.

I'll probably try nextjs then especially if it easily integrates with PG-Promise, otherwise I guess I can build a api using express but that sounds like twice the work imho

huhu
Feb 24, 2006
Anyone know how Set ended up implemented the way it is in javascript? I am quite baffled by Set.keys() vs Set.values() vs Set.entries(). It also appears union, intersection and difference weren't actually implemented, you need to convert to an array?

Edit: And also Maps. "The keys of an Object are Strings, where they can be any value for a Map. " Why is this useful?

huhu fucked around with this message at 19:19 on Jan 23, 2021

Ola
Jul 19, 2004

huhu posted:

Anyone know how Set ended up implemented the way it is in javascript? I am quite baffled by Set.keys() vs Set.values() vs Set.entries(). It also appears union, intersection and difference weren't actually implemented, you need to convert to an array?

Edit: And also Maps. "The keys of an Object are Strings, where they can be any value for a Map. " Why is this useful?

Set's keys and values are for looking up whatever the set contains efficiently, it might be a very complex object. If you find you need to iterate through it or keep track of keys and values, maybe it's not the right data structure for the job. I don't know how it ended up as it is, but it's fair to say it's not a native thing since day 1 so there's bound to be a bit of scaffolding.

While I'm sure there are plenty of libraries with union functions etc if it isn't standard, a union or an intersection isn't a property of one set, therefore it doesn't make that much sense to have that function belong to the set itself. Whereas the entries do, so set.entries() does.

As for maps, I guess it might be useful if you would otherwise have to write a hashcode for whatever it is that you use to look up values with. There are other advantages to using maps over objects outlined here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map Hashmaps are one of my favorite data structures, so I'd probably use it just to feel cool.

Ola fucked around with this message at 19:50 on Jan 23, 2021

smackfu
Jun 7, 2004

There’s a tc39 proposal to add the set theory operators for Set: https://github.com/tc39/proposal-set-methods

Page contains links to polyfills too.

Sets were only added in ES6.

TheFluff
Dec 13, 2006

FRIENDS, LISTEN TO ME
I AM A SEAGULL
OF WEALTH AND TASTE

huhu posted:

Anyone know how Set ended up implemented the way it is in javascript? I am quite baffled by Set.keys() vs Set.values() vs Set.entries(). It also appears union, intersection and difference weren't actually implemented, you need to convert to an array?

Edit: And also Maps. "The keys of an Object are Strings, where they can be any value for a Map. " Why is this useful?

I assume somebody somewhere must know but when Gary Bernhardt wondered the same thing about a year ago nobody could offer a reasonable explanation. Set.keys() and Set.entries() are quite useless in practice, but I guess if you have some cursed code that treats sets and arrays the same it could maybe somehow come in handy. The lack of set operators is also quite bizarre.

As for Map, there's plenty of use cases for keying a dictionary by things that aren't strings - most obvious would be object instances or functions, but you can also use types or classes for example. In most cases you could probably achieve the same thing by just stringifying the key, but it's nice to not have to bother.

Ola posted:

While I'm sure there are plenty of libraries with union functions etc if it isn't standard, a union or an intersection isn't a property of one set, therefore it doesn't make that much sense to have that function belong to the set itself. Whereas the entries do, so set.entries() does.

Set.entries() makes no sense though (it returns an array of [value, value] for each member of the set, mimicking what Array.entries() does, except a set doesn't actually have keys so the result is nonsense).

Also, in basically every other major language the set operations are instance methods on instances of the Set type, as in someSet.intersectWith(otherSet). Off the top of my head, Python, C#, Rust and Java sets all work like this, and the proposed implementation smackfu linked to also does the same. You could of course implement standalone set operators as functions that take sets, but most set operators other than union/intersection aren't commutative so I don't think it'd be any improvement in readability to do that.

Having a Set type without the set operators is a glaring omission.

TheFluff fucked around with this message at 15:58 on Jan 24, 2021

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



TheFluff posted:

Having a Set type without the set operators is a glaring omission.

ES is a tiny language surrounded by glaring omissions, so same as it ever was, I guess.

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Hey goons hoping one of you can help out. I’m trying to get this for loop under the ArrayCheck function to run and add values, but pg-promise skips right over it and I’m not sure why. Heres my entire express code. I’m not even sure if im doing this right. Basically I have 7 line items that I need to see if there’s a value in and then push the value to the array so I can insert it into a DB :( Everything works except for the arrayCheck call, and even when I had it outside a array PG Promise would still ignore it :(

Thanks for all the help


code:
 exports.detailedbudgetpost = function (req, res, next) {
  const arrayCheck = () => {
    for (var y = 1; y >= 7; y++) {
      var x = y.toString();
      if (isEmpty(req.body.goal + x) == false) {
        values.push({
          attrib_id: 23,
          value: req.body.goal + x,
          response_id: insertedForm.response_id,
        });
      }

      if (isEmpty(req.body.descriptionofneed + x) == false) {
        values.push({
          attrib_id: 24,
          value: req.body.descriptionofneed + x,
          response_id: insertedForm.response_id,
        });
      }

      if (isEmpty(req.body.itemnumber + x) == false) {
        values.push({
          attrib_id: 25,
          value: req.body.itemnumber + x,
          response_id: insertedForm.response_id,
        });
      }

      if (isEmpty(req.body.itemdescription + x) == false) {
        values.push({
          attrib_id: 26,
          value: req.body.itemdescription + x,
          response_id: insertedForm.response_id,
        });
      }

      if (isEmpty(req.body.howmany + x) == false) {
        values.push({
          attrib_id: 27,
          value: req.body.howmany + x,
          response_id: insertedForm.response_id,
        });
      }

      if (isEmpty(req.body.vendor + x) == false) {
        values.push({
          attrib_id: 28,
          value: req.body.vendor + x,
          response_id: insertedForm.response_id,
        });
      }

      if (isEmpty(req.body.estimatedcost + x) == false) {
        values.push({
          attrib_id: 29,
          value: req.body.estimatedcost + x,
          response_id: insertedForm.response_id,
        });
      }

      if (isEmpty(req.body.estimatedtotalcost + x) == false) {
        values.push({
          attrib_id: 30,
          value: req.body.estimatedtotalcost + x,
          response_id: insertedForm.response_id,
        });
      }

      if (isEmpty(req.body.estimatedshippingcost + x) == false) {
        values.push({
          attrib_id: 31,
          value: req.body.estimatedshippingcost + x,
          response_id: insertedForm.response_id,
        });
      }

      if (isEmpty(req.body.actualcost + x) == false) {
        values.push({
          attrib_id: 32,
          value: req.body.actualcost + x,
          response_id: insertedForm.response_id,
        });
      }

      if (isEmpty(req.body.totalactualcost + x) == false) {
        values.push({
          attrib_id: 33,
          value: req.body.totalactualcost + x,
          response_id: insertedForm.response_id,
        });
      }

      if (isEmpty(req.body.totalactualshipping + x) == false) {
        values.push({
          attrib_id: 34,
          value: req.body.totalactualshipping + x,
          response_id: insertedForm.response_id,
        });
      }

      if (isEmpty(req.body.purchasedate + x) == false) {
        values.push({
          attrib_id: 35,
          value: req.body.purchasedate + x,
          response_id: insertedForm.response_id,
        });
      }

      if (isEmpty(req.body.receiptsubmitted + x) == false) {
        values.push({
          attrib_id: 36,
          value: req.body.receiptsubmitted + x,
          response_id: insertedForm.response_id,
        });
      }
    }
  }
  db.tx(async (t) => {
    const companyDetails = await t.one(
      "SELECT company_name, c.id, first_name, last_name FROM company c INNER JOIN useraccount u on c.id = u.company_id WHERE u.username = $1",
      [req.user.user]
    );

    const insertedForm = await t.one(
      "INSERT INTO formresponse(company_id, form_id) VALUES ($1, 3) RETURNING response_id",
      [companyDetails.id]
    );

    const cs = new pgp.helpers.ColumnSet(
      ["attrib_id", "value", "response_id"],
      {
        table: "formquestionresponse",
      }
    );

    const values = [
      {
        attrib_id: 20,
        value: companyDetails.company_name,
        response_id: insertedForm.response_id,
      },
      {
        attrib_id: 19,
        value: companyDetails.first_name + " " + companyDetails.last_name,
        response_id: insertedForm.response_id,
      },
      {
        attrib_id: 18,
        value: req.body.date,
        response_id: insertedForm.response_id,
      },
      {
        attrib_id: 21,
        value: req.body.licensedchildren,
        response_id: insertedForm.response_id,
      },
      {
        attrib_id: 22,
        value: req.body.currentchildren,
        response_id: insertedForm.response_id,
      }
    ];

    const arrayInsert = await arrayCheck()

    const query = pgp.helpers.insert(values, cs);
    const recordsResponse = await t.none(query);
  })
    .then((results) => {
      req.flash("info", "Your form has been succesfully submitted. Thank you!");
      res.redirect("/thanks");
    })
    .catch((error) => {
      console.log(error);
      req.flash(
        "error",
        "An error has occured. Please try again or submit a support ticket."
      );
      res.redirect("/");
    });
};

Roadie
Jun 30, 2013

Empress Brosephine posted:

Hey goons hoping one of you can help out. I’m trying to get this for loop under the ArrayCheck function to run and add values, but pg-promise skips right over it and I’m not sure why. Heres my entire express code. I’m not even sure if im doing this right. Basically I have 7 line items that I need to see if there’s a value in and then push the value to the array so I can insert it into a DB :( Everything works except for the arrayCheck call, and even when I had it outside a array PG Promise would still ignore it :(

Thanks for all the help

Your function is trying to use a bunch of things that don't exist in the function's scope and so will get undefined or immediately die to trying-to-access-a-property-of-undefined errors, and arrayInsert is going to be a Promise for undefined because arrayInsert doesn't return anything and it's not an async function. Also, your isEmpty check is always going to be false because you're adding a stringified number to what you're checking.

It's really unclear what you're even trying to do here.

Roadie fucked around with this message at 21:27 on Jan 25, 2021

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Yeah I changed them to this type of syntax if (isEmpty(req.body[`goal${x}`]))

I’m just being lazy and don’t want to write out 100 if (req.body.goal1.length > 0) if (req.body.goal2.length > 0) if statements

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



You might start by writing arrayCheck to take all the values it cares about as parameters because, as-is, it's hard to reason about what it's operating on.

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Thanks for the tip. Tried it but still no go. It’s like PG-Promise refuses to call the function

Roadie
Jun 30, 2013

Empress Brosephine posted:

Thanks for the tip. Tried it but still no go. It’s like PG-Promise refuses to call the function

Are you actually returning a value from it?

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Yeah , I think the error lies within pg-promise as it refuses to call the function, even if all thats in the function is console.log('hi'). I’m wondering if the solution is to just run a transaction sql insert twice

here’s the updated code:

code:
 exports.detailedbudgetpost = async function (req, res, next) {

  const cs = new pgp.helpers.ColumnSet(["attrib_id", "value", "response_id"], {
    table: "formquestionresponse",
  });

  const values = [
    {
      attrib_id: 20,
      value: companyDetails.company_name,
      response_id: insertedForm.response_id,
    },
    {
      attrib_id: 19,
      value: companyDetails.first_name + " " + companyDetails.last_name,
      response_id: insertedForm.response_id,
    }
  ];

  const arrayCheck = (values, insertedformresponse) => {
    for (var x = 1; x >= 7; x++) {
      if (isEmpty(req.body[`goal${x}`]) == false) {
        values.push({
          attrib_id: 23,
          value: req.body[`goal${x}`],
          response_id: insertedformresponse,
        });
      }

      if (isEmpty(req.body[`descriptionofneed${x}`]) == false) {
        values.push({
          attrib_id: 24,
          value: req.body[`descriptionofneed${x}`],
          response_id: insertedformresponse,
        });
      }
    }
    return values;
  };

  db.tx(async (t) => {
    const companyDetails = await db.one(
      "SELECT company_name, c.id, first_name, last_name FROM company c INNER JOIN useraccount u on c.id = u.company_id WHERE u.username = $1",
      [req.user.user]
    );

    const insertedForm = await db.one(
      "INSERT INTO formresponse(company_id, form_id) VALUES ($1, 3) RETURNING response_id",
      [companyDetails.id]
    );

    arrayCheck(values, insertedForm.response_id);

    const query = pgp.helpers.insert(values, cs);
    const recordsResponse = await t.none(query);
  })
    .then((results) => {
      req.flash("info", "Your form has been succesfully submitted. Thank you!");
      res.redirect("/thanks");
    })
    .catch((error) => {
      console.log(error);
      req.flash(
        "error",
        "An error has occured. Please try again or submit a support ticket."
      );
      res.redirect("/");
    });
};

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
im the worlds dumbest loving idiot, my for loop was backwards I was doing x >= 7 instead of x<=7

Roadie
Jun 30, 2013

Empress Brosephine posted:

im the worlds dumbest loving idiot, my for loop was backwards I was doing x >= 7 instead of x<=7

This is why you should map/forEach or for...of whenever possible. Can't have errors with manual loops (taps forehead) if you don't have manual loops.

Stuff like:

JavaScript code:
import { range } from 'lodash'

const rangeInclusive = (a, b) => range(a, b + 1)

const values = [
  {
    attrib_id: 20,
    value: companyDetails.company_name,
    response_id: insertedForm.response_id,
  },
  {
    attrib_id: 19,
    value: companyDetails.first_name + ' ' + companyDetails.last_name,
    response_id: insertedForm.response_id,
  },
  ...rangeInclusive(1, 7).map((x) =>
    [
      !!req.body[`goal${x}`] && {
        attrib_id: 23,
        value: req.body[`goal${x}`],
        response_id: insertedForm.response_id,
      },
      !!req.body[`descriptionofneed${x}`] && {
        attrib_id: 24,
        value: req.body[`descriptionofneed${x}`],
        response_id: insertedForm.response_id,
      },
    ].filter(Boolean)
  ),
]

(Disclaimer: off the top of my head so there's probably something broken in there, but it should give an idea)

Roadie fucked around with this message at 01:24 on Jan 26, 2021

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Roadie posted:

This is why you should map/forEach or for...of whenever possible. Can't have errors with manual loops (taps forehead) if you don't have manual loops.

I totally agree with not using regular for loops unless it's absolutely necessary.

That said, foreach has a couple of problems:

1) Break/continue doesn't work. Only way to short circuit is to throw an exception.
2) It has GC pressure issues on many platforms because an object is created for every property in the object. Not super well implemented.

I'd also recommend not using for ... in because it does weird poo poo if you try to iterate arrays.

For ... of is currently the least lovely way to foreach imo.

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
I thought I read you can't use map over objects

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Empress Brosephine posted:

Yeah , I think the error lies within pg-promise as it refuses to call the function, even if all thats in the function is console.log('hi').

and

Empress Brosephine posted:

im the worlds dumbest loving idiot, my for loop was backwards I was doing x >= 7 instead of x<=7

are describing very different things. Did you put the log call in the for loop and conclude it wasn't running the function from that?

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Yeah the log call was in the loop and then I put a log call outside the loop, saw it was being called and that's what clicked in my monkey brain. About 7 hours later

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

Empress Brosephine posted:

I thought I read you can't use map over objects

you can't but you can create an array of the object's keys or values and map over those

JavaScript code:
Object.keys(myObject).map(eachKey => {
  const someValue = myObject[eachKey]
})

// or 

Object.values(myObject).map(eachValue => {
  
})

uguu
Mar 9, 2014

What makes mithril a framework instead of a library?
I feel like it has more in common with jQuery than Vue.

necrotic
Aug 2, 2005
I owe my brother big time for this!
It looks like a virtual Dom system which is way more like Vue or React than jQuery.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Grump posted:

you can't but you can create an array of the object's keys or values and map over those

JavaScript code:
Object.keys(myObject).map(eachKey => {
  const someValue = myObject[eachKey]
})

// or 

Object.values(myObject).map(eachValue => {
  
})

I figured they were talking about Map

TheFluff
Dec 13, 2006

FRIENDS, LISTEN TO ME
I AM A SEAGULL
OF WEALTH AND TASTE

Empress Brosephine posted:

I thought I read you can't use map over objects

In addition to the already mentioned Object.keys() and Object.values(), Lodash provides _.mapKeys() and _.mapValues(), which are super handy for the pretty common case where you want to apply some kind of transformation to each of an object's keys or values but you don't want to mutate the object in place. So, for a trivial example,

code:
const lowercase = {
  foo: 'abc',
  bar: 'xyz',
};
const uppercase = _.mapValues(lowercase, (value) => value.toUpperCase());
// results in { foo: 'ABC', bar: 'XYZ' } without mutating the lowercase object
Should be noted though that there are no guarantees about the iteration order with these.

Adbot
ADBOT LOVES YOU

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Oh that's sweet, these are some cool tools thanks goons. I hope to be able to share my finished project :D

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply