Lodash 4: How to omit Object properties if they contain a certain part of a string? - lodash

Is it possible to use Lodash's omit method and remove keys that may contain the string _old appended to them ?
For example, here is my JSON object:
{
"name": "Canada",
"shortName": "CanadaEH",
"shortName_old": "Canada",
"fullName": "The NEW Republic of Canada",
"fullName_old": "The Republic of Canada",
...etc...
}
I have imported the omit package in my app like so:
import { omit } from 'lodash'
This works when I do this :
filteredFields() {
return omit(this.myObj, ['name'])
}
I get back the object without those omitted properties just as expected.
However, adding it like so does not work:
return omit(this.myObj, ['name', '_old'])
How can I also omit the keys that may contain _old ?

The _.omitBy() method accepts a predicate function, which is called with the current value and key of the property. You can then check the key for the existence of the string.
const obj = {
"name": "Canada",
"shortName": "CanadaEH",
"shortName_old": "Canada",
"fullName": "The NEW Republic of Canada",
"fullName_old": "The Republic of Canada",
}
const result = _.omitBy(obj, (v, k) => k.endsWith('_old'))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Related

Remove repeating text and quotes in Child component in Vue JS

I'm looking for some help to remove duplicate words, commas and [] in an array of objects output in a child component.
PARENT
<Countries
v-for="(result, index) in countries"
:result="result"
:index="index"
/>
CHILD
<div v-if="country" >
{{country}}
</div>
mounted () {
this.country = [...new Set(this.result.results.country)];
},
data: function () {
return {
name: this.result.results.country
}
JSON data
"result": [
"results": {
"country": "Poland, France, Germany, Poland, Latvia, Estonia, Germany, Germany, France",
},
"results": {
"country": "Poland, France, Germany, Poland, Latvia, Estonia, Germany, Germany, France",
},
"results": {
"country": "Poland, France, Germany, Germany, France",
},
"results": {
"country": "Greece, Spain",
},
.....
This is the OUTPUT I am getting
[ "G", "r", "e", "c", ", ",", "S", "p", "a", "i", "n",", " ]
It splits the data and removes duplicate letters. How can I get it to just split the words, remove duplicate entries and remove the quotes and the commas?
So the output would just be
Greece, Spain
Thank you
Try to split the string by ', ' and create the set based on the array from the split result :
this.country = [...new Set(this.result.results.country.split(', '))];
We are using Set object is to remove the duplicates from an input which could be any iterable value. i.e. string or an array.
If we are passing a string, it will check character by character and remove duplicate characters.
If we are passing an array, it will check element by element and remove the duplicate elements.
As per your requirement, First you have to convert that countries string into an array by using Array.split() method and then you can remove the duplicate names.
Live Demo :
const country = "Poland, France, Germany, Poland, Latvia, Estonia, Germany, Germany, France";
const arr = country.split(', ');
console.log([...new Set(arr)].join());
You should split the CSV string
mounted () {
this.country = [...new Set(this.result.results.country.split(',')];
}

How do I query referenced document fields within an array of objects in Sanity with GROQ?

I have a document which has an array of objects of which one of the fields is a reference to another document. The following query returns the referenced document _id and _type only, and I need other fields from those documents.
// GROQ query
*[slug.current == $slug]{
title,
slug,
objectArray
}
This results in:
"result": [
0: {
"title": "Test Document"
"slug": {
"_type": "slug"
"current": "test-document"
}
"objectArray": [
0: {...}
1: {
"_key": "583ec1dee738"
"_type": "documentObject"
"objectTitle" : "Test Object"
"documentReference": {
"_ref": "2f9b93b4-4924-45f2-af72-a38f7d9ebeb4"
"_type": "reference"
}
"booleanField": true
}
]
}
]
documentReference has its own set of fields (ie. title) in the schema which I need to be returned in my query.
How do I do this?
I have looked at the Sanity documentation at joins and object projections, but I cannot get the syntax right for when the reference is within an array of objects.
You need to do a join on the reference:
*[slug.current == $slug] {
title,
slug,
objectArray[] {
documentReference->
}
}
The syntax objectArray[] can be thought of as "for each element", and -> does a join to look up the referenced document. In other

Multiple Patterns for Regex Expression MongoDB Atlas

I'm trying to get a MongoDB aggregate pipeline working. I need to match name to "John" and regex their "hometown" field to regex matching "CAPETOWN" or "FLORIDA" without case sensitivity. Basically if either of those patterns exist in the "hometown" field of the document. This is what I have so far.
const news = await cachedDb.collection(COLLECTION).aggregate([
{ $match: { "name": "John", "hometown": { $regex: /CAPETOWN/, $options: 'i' } } }
]).toArray();
I can only get CAPETOWN included, I want an OR. Such as "hometown" contains CAPETOWN OR FLORIDA with option (i). How do I go about doing that?
You have to set OR directly in the regex string.
db.collection.aggregate([
{
$match: {
"hometown": {
$regex: "CAPETOWN|FLORIDA",
$options: "i"
}
}
}
])
You can test it here

I'm storing axios response into two different "data" variables, if I change one variable it will automatically changes other variable

In the below html code , I'm simply iterating through 2 variables posts and cp_posts:
HTML CODE
<div v-if="loading">
loading...
</div>
<div v-else>
<p style="background:#ebebeb" v-for="post in posts">
{{post}}
</p>
<p style="background:#ebaaeb" v-for="post in cp_posts">
{{post}}
</p>
</div>
</div>
In the below Vue script, I'm making one axios call to demo URL for fetching some dummy data. Once the request is done I'm storing response data into locally defined variable i.e temp, after that I'm assigning temp to Vue data variables posts and cp_posts.
After assignment I'm changing posts variable, that's it.
const URL = 'https://reqres.in/api/users';
new Vue({
el: '#app',
data() {
return {
loading: true,
posts: [], // add posts here so reactivity is working, also undefined would be OK
cp_posts: []
}
},
created() {
//this.loading = true --> not needed already set in data
axios.get(URL).then((response) => {
// console.log(response.data, this)
var temp = response.data.data
this.posts = temp
this.cp_posts = temp
this.posts[0].id = 4444 // <== Here I'm changing value from posts variable which will change cp_posts
this.loading = false
})
}
})
OUTPUT
You can see cp_posts variable ==> id: 4444 also get changes, which should be 1, because I haven't touch cp_posts variable in above code
variable : posts
{ "id": 4444, "first_name": "George", "last_name": "Bluth", "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg" }
{ "id": 2, "first_name": "Janet", "last_name": "Weaver", "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg" }
{ "id": 3, "first_name": "Emma", "last_name": "Wong", "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg" }
variable : cp_posts
{ "id": 4444, "first_name": "George", "last_name": "Bluth", "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg" }
{ "id": 2, "first_name": "Janet", "last_name": "Weaver", "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg" }
{ "id": 3, "first_name": "Emma", "last_name": "Wong", "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg" }
Why cp_post variable also get changes while changing post variable?
Ref Link:
https://jsfiddle.net/LokeshKhandare/31zvmcwp/2/
In posts and cp_posts, they have the reference of temp that make it mutable.
So what you can do is you can change this line
this.cp_posts=temp
to
this.cp_posts=JSON.parse(JSON.stringify(temp))
This will solve your problem. JSFiddle Link
The reason why cp_posts is also changed is that in JS arrays and objects are reference type values which means they reference to address of the value in Memory. If you change the value they all changes. One way I found to solve is from this medium post:
//Deep Clone
let a = [{ x:{z:1} , y: 2}];
let b = JSON.parse(JSON.stringify(a));
b[0].x.z=0
console.log(JSON.stringify(a)); //[{"x":{"z":1},"y":2}]
console.log(JSON.stringify(b)); // [{"x":{"z":0},"y":2}]

Parse Cloud Hosting Truncating User Results

I'm having a strange issue with Parse's Cloud Hosting platform. I have a route that displays info on all 'Providers' in my system. A Provider has a column that is a Pointer to a User object. This is a special Parse.User object.
My goal is to get all Providers and the User info that the provider points to. Seems simple, using the "include" method for the query.
The route code looks like this:
exports.index = function(req, res) {
var providersQuery = new Parse.Query('Provider');
providersQuery.include('user');
providersQuery.find().then(function(providers) {
console.log(providers); //for debugging
res.render('providers/index', { providers: providers });
});
};
Here's where things get weird. The above log statement shows all Providers with all the User data included:
[{ "address": "123 Main St.", "city": "Anytown", "zip": "77777",
"user":
{ "email": "john.smith#example.com", "firstName": "John", "lastName": "Smith", "objectId": "abcd123", "__type": "Object", "className": "_User" }
}]
Notice that the __type is "Object".
However, in my view the User object data is truncated and only shows __type, className, and objectId fields:
//index.ejs
<%- JSON.stringify(providers) %>
Results in the following:
[{ "address": "123 Main St.", "city": "Anytown", "zip": "77777",
"user":
{ "objectId": "abcd123", "__type": "Pointer", "className": "_User" }
}]
All the info about the user is gone!! And the __type is now "Pointer". What the hell is going on?
Apparently calling JSON.stringify on Parse object will return "included" objects back to their "Pointer" selves. I'm sure there is some good reason for this, but it's certainly inconvenient.