Destructuring objects in Javascript - javascript

In my code base I have an object:
let myObject = {
"version": 1,
"traceId": "123456789",
"session": {},
"trigger": {
"service": "some_service_is_here",
"action": "update",
"resource": "transaction"
},
"changesets": [
{
"update": {
"retryCount": 1
},
"conditions": {
"equal": {
"subscriptionId": "aaaaaaaaaaaa",
"transactionId": "bbbbbbbbbbbb"
}
}
},
{
"update": {
"retryCount": 2
},
"conditions": {
"equal": {
"subscriptionId": "ccccccccccccc",
"transactionId": "dddddddddddddd"
}
}
}
]
}
I need to extract some properties from that object. So far it is done using Lodash. There are more extractions going on, but they are fairly identical. Several examples of using it with Lodash:
const trigger = _.get(myObject, 'trigger', null);
const retryCount = _.get(myObject, 'changesets[0].update.retryCount', null);
It works and behaves as expected. I would like to improve this code, by eliminating Lodash and start using Destructuring.
So far I have this:
const trigger = _.get(myObject, 'trigger', null);
becomes
const {trigger} = myObject;
And also:
const retryCount = _.get(myObject, 'changesets[0].update.retryCount', null);
becomes
const {changesets: [{update:{retryCount:retryCount = null}}]} = myObject;
It also works, test are passing:
Now I have several questions:
Is this the correct practice to extract those values?
Is it worth it, in terms of speed and code readability?
The second destructuring example. I will receive an changeset array, that has many objects (unknown number), but I am always interested in the first one. The lodash example illustrates that. When I destructure, I do not specify that I need a first one (zero based) it comes in by default. Do I need somehow to specify I need the zeroth one, or it is default behaviour?

Yes, but currently your variants are not equal. You need to specify null to be default value in variant with destructuring .
Code is not faster. As for readability - it depends.
You currently specify index explicitly by items' position in the list. So for example
const {changesets: [,,{update}]} = myObject;
would explicitly extract 3rd element. You don't need to do anything extra.
PS retryCount:retryCount better don't specify the same name twice. it looks confusing. Reader(like me) will re-read for several times trying to figure out the difference.

Related

Update single object in localStorage

I want to update a single Object in my localStorage. I made a detail page, where I can submit new values (progress and value)
When I want to update the value, it changes the value in both objects. How can I change just one object.
Here is my deployment link.(its work in progress)
https://mastery-app.herokuapp.com/
This is my localStorage array:
skills[
{
"title": "Sewing",
"imageSrc": "images.unsplash.com",
"description": "Make your own clothes",
"category": "crafting",
"progress": 500,
"isDone": false,
"rank": 0,
"value": 0
},
{
"title": "Crocheting",
"imageSrc": "images.unsplash.com",
"description": "Interlock loops of yarn",
"category": "crafting",
"progress": 500,
"isDone": false,
"rank": 0,
"value": 0
}
]
This is how I update the localStorage:
const update = skills.map((skills) => {
skills.title === skills.title;
const updateProgress = skills.progress - value;
const rankNumber = parseInt(ranking);
const updateRank = skills.rank + rankNumber;
console.log(updateRank);
const updateValue = skills.value + value;
return {
title: skills.title,
rank: updateRank,
description: skills.description,
progress: updateProgress.toFixed(1),
imageSrc: skills.imageSrc,
category: skills.category,
isDone: false,
value: updateValue,
};
});
localStorage.setItem('skills', JSON.stringify(update));
You may consider using the find method to find the object you want to update. map is not the right function to be used for your use case.
Also skills.title === skills.title; has no effect at all (Maybe you wanted to use an if statement to do some kind of filtering by using title but that always would return true). Please remove that.
Now, I don't exactly know which field are you going to use to search for the object you want to update, but it has to be unique. If none of the fields in the objects are unique you should consider adding an unique id field in the skills objects. But if title is unique you can use the title to search. Then you can do something like the pseudo code below:
const toUpdate = skills.find(skill => skill.title === your_title_here)
toUpdate.field_to_update_1 = some_value_1
toUpdate.field_to_update_2 = some_value_2
localStorage.setItem('skills', JSON.stringify(skills))
Please also check the MDN docs to see how map, find and other array methods work and some of their use cases.

Array - What's the best way to check a value exists in one of the array elements (React / JS)

So this is an example data array that I will get back from backend. There are a few use cases as shown below and I want to target based on the subscription values in the array.
Example: 1
const orgList = [
{ id: "1", orgName: "Organization 1", subscription: "free" },
{ id: "2", orgName: "Organization 2", subscription: "business" },
];
In the example 1 - when array comes back with this combination - there will be some styling and text to target the element with subscription: free to upgrade its subscription
Example 2:
const orgList = [
{ id: "1", orgName: "Organization 1a", subscription: "pro" },
{ id: "2", orgName: "Organization 2a", subscription: "business" },
];
Example 3:
const orgList = [
{ id: "1", orgName: "Organization 1b", subscription: "free" },
];
In the example 3 - when array comes back with only one element - there will be some styling and text to target the element say to upgrade its subscription
At the moment, I'm simply using map to go over the array that I get back like so:
{orgList.map((org) => (...do something here)} but with this I'm a bit limited as I don't think this is the best way to handle the 3 use cases / examples above.
Another idea is too do something like this before mapping but this:
const freeSubAndBusinessSub = org.some(org => org.subscription === 'free' && org.subscription === "business")
but doesn't seem to work as it returns false and then I'm stuck and not sure how to proceed after..
So my question is what's the best way to approach this kind of array to target what do to with the elements based on their values?
You mention that using .map() is limited, but you don't expand on it. Logically what it sounds like you want is a separate list for each type to act upon. You can accomplish this using .filter() or .reduce(), however, in this case .map() is your friend.
// Example 1
const free = orgList.filter(org => org.subscription === 'free');
const business = orgList.filter(org => org.subscription === 'business');
free.map(org => /* do free stuff */);
business.map(org => /* do business stuff */);
// Example 2
const subscriptions = orgList.reduce((all, cur) => {
if (!all.hasOwnProperty(cur.subscription)) {
all[cur.subscription] = [];
}
all[cur.subscription].push(cur);
return all;
}, {});
subscriptions['free'].map(org => /* do free stuff */);
subscriptions['business'].map(org => /* do business stuff */);
// Example 3
orgList.map(org => {
switch(org.subscription) {
case 'free':
/* do free stuff */
break;
case 'business':
/* do business stuff */
break;
}
})
You'll notice that in all the examples, you still need to map on the individual orgs to perform your actions. Additionally, with the first two examples, you'll be touching each element more than once, which can be incredibly inefficient. With a single .map() solution, you touch each element of the list only once. If you feel that you do free stuff actions become unwieldy, you can separate them out in separate functions.

How to deep watch an object in angularjs excluding a specified pattern?

There is an nested object with certain properties which i don't want to be watched. It could be a pattern of properties starting with perhaps "_".
Here's a sample structure.
$scope.ObjectToBeWatched = {
"company": {
"ts": {
"_msg": {"nm":""},
"status": "success"
},
"ids": [
"000000010",
"000000011"
]
},
"_f": [
{
"code": "TY_IO",
"status": "fail"
}
]
}
Standard deep watch:
$scope.$watch("ObjectToBeWatched",function(newObj,oldObj){
},true);
Right now the watch is firing for any any change in any properties which is expected. So in above case any changes to properties
_msg, _f
should not fire.
Thanks for help.
You can try something like this:
$scope.$watch(function($scope) {
return $scope.listOfBigObjects.
map(function(bigObject) {
return bigObject.foo.
fieldICareAbout;
});
}, myHandler, true);
This grabs only the props you care about from the objects in an array. You can use an expression to check for certain field types inside the object map. If you don't have an array just skip that part.
Underscore has tons of functional methods to help w/ this as well if 'map' isn't exactly what you need to return fields you care about.

Cannot infer query fields to set error on insert

I'm trying to achieve a "getOrCreate" behavior using "findAndModify".
I'm working in nodejs using the native driver.
I have:
var matches = db.collection("matches");
matches.findAndModify({
//query
users: {
$all: [ userA_id, userB_id ]
},
lang: lang,
category_id: category_id
},
[[ "_id", "asc"]], //order
{
$setOnInsert: {
users: [userA_id, userB_id],
category_id: category_id,
lang: lang,
status: 0
}
},
{
new:true,
upsert:true
}, function(err, doc){
//Do something with doc
});
What i was trying to do is:
"Find specific match with specified users, lang and category... if not found, insert a new one with specified data"
Mongo is throwing this error:
Error getting/creating match { [MongoError: exception: cannot infer query fields to set, path 'users' is matched twice]
name: 'MongoError',
message: 'exception: cannot infer query fields to set, path \'users\' is matched twice',
errmsg: 'exception: cannot infer query fields to set, path \'users\' is matched twice',
code: 54,
ok: 0 }
Is there a way to make it work?
It's impossible?
Thank you :)
It's not the "prettiest" way to handle this, but current restrictions on the selection operators mean you would need to use a JavaScript expression with $where.
Substituting your vars for values for ease of example:
matches.findAndModify(
{
"$where": function() {
var match = [1,2];
return this.users.filter(function(el) {
return match.indexOf(el) != -1;
}).length >= 2;
},
"lang": "en",
"category_id": 1
},
[],
{
"$setOnInsert": {
"users": [1,2],
"lang": "en",
"category_id": 1
}
},
{
"new": true,
"upsert": true
},
function(err,doc) {
// do something useful here
}
);
As you might suspect, the "culprit" here is the positional $ operator, even though your operation does not make use of it.
And the problem specifically is because of $all which is looking for the possible match at "two" positions in the array. In the event that a "positional" operator was required, the engine cannot work out ( presently ) which position to present. The position should arguably be the "first" match being consistent with other operations, but it is not currently working like that.
Replacing the logic with a JavaScript expression circumvents this as the JavaScript logic cannot return a matched position anyway. That makes the expression valid, and you can then either "create" and array with the two elements in a new document or retrieve the document that contains "both" those elements as well as the other query conditions.
P.S Little bit worried about your "sort" here. You may have added it because it is "mandatory" to the method, however if you do possibly expect this to match "more than one" document and need "sort" to work out which one to get then your logic is slightly flawed.
When doing this to "find or create" then you really need to specifiy "all" of the "unique" key constraints in your query. If you don't then you are likely to run into duplicate key errors down the track.
Sort can in fact be an empty array if you do not actually need to "pick" a result from many.
Just something to keep in mind.

How to get the name of the array in json data using JavaScript

I have a JSON object which comes back like this from a JavaScript API call:
{
"myArray": [
{
"version": 5,
"permissionMask": 1
},
{
"version": 126,
"permissionMask": 1
}
]
}
How can I access the name of the array (i.e myArray) in JavaScript. I need to use the name of the array to determine the flow later on.
Use getOwnPropertyNames to get a list of the properties of the object in array form.
Example:
var myObj = {
"myArray": [
{
"version": 5,
"permissionMask": 1
},
{
"version": 126,
"permissionMask": 1
}
]
},
names = Object.getOwnPropertyNames(myObj);
alert(names[0]); // alerts "myArray"
Note: If the object can have more than one property, like myArray, myInt, and myOtherArray, then you will need to loop over the results of getOwnPropertyNames. You would also need to do type-testing, as in if(names[0] instanceof Array) {...} to check the property type. Based on your example in your question, I have not fleshed all of that out here.
Object.keys(data)[0]
# => "myArray"
A terminology note: This solution assumes you have a JavaScript object. You might have a JSON string, in which case this is the solution:
Object.keys(JSON.parse(data))[0]
# => "myArray"
However, "JSON object", in JavaScript, is just one - the one I used just now, that has JSON.parse and JSON.stringify methods. What you have is not a JSON object except perhaps in a trivial interpretation of the second case, where all values in JavaScript are objects, including strings.
The other answers are good if you have no control over the return format.
However, if you can, I'd recommend changing the return format to put the important values you care about as actual values instead of keys to make it clearer. For example, something like this:
result =
{
"name: "myArray",
"value": [
{
"version": 5,
"permissionMask": 1
},
{
"version": 126,
"permissionMask": 1
}
]
}
Then, it's a lot clearer to reliably access the property you care about: result.name

Categories