_.matchesProperty shorthand in Lodash not working but providing function does - javascript

I'm pretty new to Lodash and I'm having some problems with the shorthand notation on the _.find function.
I have the following angular 2 object:
export class ProductData {
id: number;
name: string;
description: string;
type: ProductTypeData;
}
I then have an array of ProductData that I created by filtering on product type. I use this array to display values in a dropdown list on to the user. When the user selects a product from the dropdown list I am storing the id in a local variable, productId. When the user closes the dialog I am doing processing on the selected product.
The following code works for me:
var self = this;
let selectedProduct = _.find(this.filteredProducts, function(product) { return product.id == self.productId; });
I would rather use the _.matchesProperty shorthand for Lodash (since it's cleaner to read than assigning the context to a variable) like so:
let selectedProduct = _.find(this.filteredProducts, ['id', this.productId]);
but that is returning undefined for me.
I'm guessing I'm screwing up something fairly simple but I cannot, for the life of me, figure out what.

Related

Getting a property of objects in an array, as an array, using Formik's useField hook

Given a Formik context containing an array of objects:
{
myArrayOfObjects: {
property: string
}[]
}
I would like to get an array of the values of property. I don't, however, have any idea whether this is possible. For further reference, I initially attempted myArrayOfObjects.property and myArrayOfObjects[].property in the hopes it would magically work, but unfortunately it does not.
The end goal here is to use this in tandem with a react-select multiselect field.
Is this possible, and if not, what would be the proper way to work this out properly?
This is on formik v2.2.6
You can transform the data to get the array. There are possible better ways to do it, but this is the idea:
const getPropertyValues = (values: InnerObject[]) => {
const newArray: string[] = [];
values.map((x: InnerObject) => {
newArray.push(x.properties);
});
return newArray;
};
I did a CodeSandbox so you can try it. I use that same function in 2 places:
To print the values of the form as an string[]
In the SelectComponent to create the options that will be displayed on the react-select component

Javascript: How does using a class benefit over creating objects at the time they are needed?

I am unsure of why I would exactly need to use a class here or perhaps a better way to say it is: I am not sure how a class is helpful as opposed to just forming objects on the fly.
export default class Car {
constructor(type="not specified", engine="V6") {
this.type = type;
this.engine = engine;
}
getType() {
return `the car type is ${this.type}`
}
}
main.js
import Car from Car.js;
let allCars = [];
function userSubmittedCarInfo() {
let typeValue = document.getQuerySelector('.input-type').value;
let engineValue = document.getQuerySelector('.input-engine').value;
// not sure the difference of just sending data as an object vs sending as class object?
//option 1 .... for object on the fly that I can post to server. Push it to list if I
// need a running list of all objects later on.
let obj = {
type: typeValue,
engineValue: engineValue,
}
allCars.push(obj);
//option 2... second option is create an instance of Car class
let obj = new Car(typeValue, engineValue)
fetch('url-i-am-posting-to', {
car: obj
})
}
Classes are generally useful when you want to tie together data with methods that operate on that data. Your Car here gives instances both properties on the instance (data) as well as a method that operates on the data (getType).
If you actually do want to call the getType method at certain points in the code, or if you add additional methods on the Car, having a class is quite a reasonable choice - you just have to pass in the data, and it'll return an object containing both the data and useful methods for that data.
But if you don't need methods - like in this example, it doesn't look like you're ever calling getType - then a class may well not provide any benefit, and could be considered to only be adding confusing overhead, and using an object literal would make good sense instead (arguably, even more sense).

Problem in handling many field through function in mongoose

I want to generate field in mongoose with function.
Because there are many fields, but they are much the same, I wanna use function to create them to keep code short.
I wrote a function, but there exists lints.
import { Schema } from 'mongoose'
function fieldGen(name, type="string", isRequired=true) {
var field = {}
field[name] = {
type: type,
required: isRequired
}
return {...field}
}
const testSchema = new Schema({
fieldGen("firstname")
fieldGen("lastname")
fieldGen("location")
})
In VS Code, Problem shows as below
Identifier expected. ts(1003) [20, 12]
I expect first argument "firstname" matches name in function, and return object.
You're adding values to your testSchema object without giving them names.
Also, you're spreading the properties of the field object into a new object literal. That doesn't accomplish anything. Just returning the field object would yield the same result.
I see what you are trying to do. If you debug this in smaller steps and take a closer look at the data you are handling, I think you'll figure it out on your own.

How to set default module params in Javascript

so i'm trying my hands on writing my very first library module using pure javascript except that i just hit a snag and need a little bit of help.
I'm using Revealing module pattern because of its neatness. In my module i have my default params in an object like this.
var defaults = {
name : 'John Doe',
age : 'Unspecified,
height : '5feet'
};
And this works splendid, but i have an init function where a user can pass an object with these keys. e.g
Module.init({
name : 'james',
age : 12
});
Now in my code, i try to write a function that returns the values of each of these keys comparing the default values and the initialized one. If the key/value exists initialized, it should return it else use default. I know what i want, but don't know how to check the objects keys just yet.
function getValues (defaultObject, initObject){
//scans the keys and returns the values
}
So in code i can do stuff like
var options = getValues(defaultObject, initObject);
var name = options.name;
This means that name will either be james if specified or john doe if not. Also for height since i didn't set a value, i get the default too
Thanks in advance guys.
What you need to do to compare both objects keys, and if the new object has a key, then replace the value in the old one. Here's an example:
function getValues(defaultObject, initObject) {
for (var key in initObject) {
if (initObject.hasOwnProperty(key)) {
defaultObject[key] = initObject[key];
}
}
return defaults;
}
I hope this help you.
See my answer in another thread how to
better define function optional default params : https://stackoverflow.com/a/52082835/1422407
It may help you to redefine function signature, and as result less useless logic in function itself.

Ember - Using controller functions in other controller functions

I am trying to create a page that shows a list of products with filtering and multiple ways of sorting the list. Rather than repeating the filtering code for each sort, I wanted to start each of the sorting methods with a call to the filtering method. I can currently filter by name:
filterText: '',
filteredResults: function() {
var filterText = this.get('filterText');
var regexp = new RegExp(filterText,'gi');
var causes = this.get('model.products').filter(function(name){
return name.get('name').match(regexp);
});
return causes;
}.property('filterText'),
However I now want to use this function in the sort methods. I've tried using Ember.computed.sort :
priceAscSorting: ['price'],
sortPriceAsc: Ember.computed.sort('filteredResults', 'priceAscSorting'),
but it seems like it treats the first input as null if I stick it in a template. If I try calling the filter method inside the sorting method:
priceAscSorting: ['views'],
sortPriceAsc: function() {
var products = filteredResults();
}
Ember throws a compiler error saying 'filteredResults' is not defined. How can I access my filter methods to use in my sorting methods?
Your code is correct, it will take filteredResults computed property and return sorted result in ascending order by using price key.
priceAscSorting: ['price'],
sortPriceAsc: Ember.computed.sort('filteredResults', 'priceAscSorting'),
but it seems like it treats the first input as null if I stick it in a
template
that means you need to check filteredResults computed property

Categories

Resources