This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 3 years ago.
For deeper understanding purpose i used val.key instead of val[ ] at function extractKey which i thought would give me [ name, name, name, name ] as result but instead i get [undefined, undefined, undefined, undefined] Why is this ? :
function extractKey(arr, key){
return arr.map(function(val){
return val.key;
})
}
extractKey([{name: 'Elie'}, {name: 'Tim'}, {name: 'Matt'}, {name:
'Colt'}], 'name') // ['Elie', 'Tim', 'Matt', 'Colt']
(4) [undefined, undefined, undefined, undefined]
Use (square brackets) array notation instead of (dot) object notation.
function extractKey(arr, key) {
return arr.map(function(val) {
return val[key];
})
}
const names = extractKey([{
name: 'Elie'
}, {
name: 'Tim'
}, {
name: 'Matt'
}, {
name: 'Colt'
}], 'name'); // ['Elie', 'Tim', 'Matt', 'Colt']
console.log(names);
Related
Let say that I have these two nested objects:
const sourceKeys = {
school: {
name: "Elisa Lemonnier",
students: 250
},
house: {
room : 2,
kids: true,
assets: "elevator",
}
}
const targetKeys = {
school: {
name: "Lucie Faure",
students: 150,
address: "123 Main St.",
phone: "555-555-5555"
},
house: {
room : 4,
kids: false,
assets: "Garden",
shop: "Auchan"
}
}
And I want the targetKeys keep ONLY the keys that are in sourceKeys. So I will get that :
const targetKeysMatchingSourceKeys = {
school: {
name: "Lucie Faure",
students: 150,
},
house: {
room : 4,
kids: false,
assets: "Garden",
}
}
I don't know how to proceed given that is a nested object. So, I will appreciate any help.
thanks you
I have find the solution, here is
const filteredJSON = Object.assign({}, TargetJsonToObject)
// Recursive function to filter the properties of the object
function filterObject(SourceJsonToObject, filteredObj) {
for (const key of Object.keys(filteredObj)) {
// If the key is not present in the source JSON, delete it from filtered JSON
if (!SourceJsonToObject.hasOwnProperty(key)) {
delete filteredObj[key]
} else if (typeof filteredObj[key] === "object") {
// If the key is present in the source JSON and the value is an object, recursively call the function on the nested object
filterObject(SourceJsonToObject[key], filteredObj[key])
}
}
}
filterObject(SourceJsonToObject, TargetJsonToObject)
This question already has answers here:
How to validate array of objects using Joi?
(6 answers)
Closed last year.
I am using bellow code:
const coll = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jemmy' },
{ id: 3, name: 'Jenny' }
];
const schema = Joi.object().keys({
name: Joi.string().min(3).required()
});
return schema.validate(coll);
when my coll array is valid, then also when checking the schema, it shows the following, always going to the error section.
schema validator
{
value: [
{ id: 1, name: 'Action' },
{ id: 2, name: 'Horror' },
{ id: 3, name: 'Comedy' }
],
error: [Error [ValidationError]: "value" must be of type object] {
_original: [ [Object], [Object], [Object] ],
details: [ [Object] ]
}
}
If you want to validate an array containing objects, you could use
const schema = Joi.array().items(Joi.object().keys({
name: Joi.string().min(3).required()
}))
I am using TypeOrm in my node.js project. I know to find a record from database I can do :
userRepository.find({ where: { firstName: "John" } });
It executes query:
SELECT * FROM "user"
WHERE "firstName" = 'John'
But now I need do add another filed check in "where" condition only if the value is presented. For example, I want to also check company in SQL "where" condition, but only if company value is presented.
I tried following, I wonder can I do the following by giving a default empty string '' if company doesn't present then pass it to find function's where?
const company = params.company ? params.company : '';
userRepository.find({ where: { firstName: "John", company: company } });
But it would still add "company"='' in the final SQL query which is not good. I wonder is there an existing function in TypeORM that could dynamically decide only add more condition in where if value is presented and not empty string?
You can use destruction for it. Like:
userRepository.find({
where: {
firstName: "John",
...(params?.company && { company: params.company }),
}
});
so, if params.company is undefined (or empty string) then
...(undefined && { company: undefined })
returns undefined and for the destruction it like ...{} for you.
if params.company contain some value, the
...('company' && { company: 'company' })
returns ...{company: 'company'} and destruct this for your where.
Example:
const companyTestWithValue = 'company';
const companyTestWithoutValue = '';
const whereWithValue = {
firstName: 'John',
...(companyTestWithValue && { company: companyTestWithValue }),
};
const whereWithoutValue = {
firstName: 'John',
...(companyTestWithoutValue && { company: companyTestWithoutValue }),
};
console.log('whereWithValue:', whereWithValue);
console.log('whereWithoutValue:', whereWithoutValue);
You can create a find condition dynamically, example:
const condition = { where: { firstName: "John" } };
if (params.company) {
condition.where = {
...condition.where,
company: params.company
}
}
const user = userRepository.find(condition);
Note that you don't get type safety when using spread operator. Instead you can conditionally set the property to undefined. Undefined properties in the where clause are excluded from the query. Nulls however are included.
So instead of:
userRepository.find({
where: {
firstName: "John",
...(params?.company && { company: params.company }),
}
});
You can write:
userRepository.find({
where: {
firstName: "John",
company: params?.company ? params.company : undefined,
}
});
userRepository.find({
where: {
firstName: "John",
company: params?.company || undefined,
}
});
Or with nested properties:
userRepository.find({
where: {
firstName: "John",
company: params?.company?.name && { name: params.company.name } || undefined,
}
});
userRepository.find({
where: {
firstName: "John",
company: { name: params?.company?.name || undefined},
}
});
I don't think there will be a pretty solution to this. Your best bet will probably to just use an if - else statement. TypeOrm will create a statement using whatever was passed to it. I suggest just doing:
if(params.company){
userRepository.find({ where: { firstName: "John", company: company } });
} else{
userRepository.find({ where: { firstName: "John" } });
}
I am trying to figure out how to query the nested objects inside the Components object. The data was inserted from a parsed json file.
Query
var query = {}
cursor = db.collection("workflows").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
This data is returned when I run the query above:
At this point i'm just trying to get it to filter in some manner. I've tried Name:'Test WF' and other variations of that but still can't get a filtered response.
[ { _id: 5c77040838f9d322b89bbd82,
texto:
{ _id: 12,
LocalCachePath: 'Z:\\Test\\Cache',
SharedCachePath: [],
Name: 'Test WF',
Desc: 'I\'m testing',
Components: [Array] } },
{ _id: 5c7704164413692978a9dd1a,
texto:
{ _id: 'Workflow-2019.02.22-23.21.15-MKRU',
LocalCachePath: 'Z:\\MAITest\\Cache',
SharedCachePath: [],
Name: 'Test WF',
Desc: 'I\'m testing',
Components: [Array] } },
{ _id: 5c77046335b012379c99951b,
texto:
{ _id: '154',
LocalCachePath: 'Z:\\Test\\Cache',
SharedCachePath: [],
Name: 'Test WF',
Desc: 'I\'m testing',
Components: [Array] } },
{ _id: 5c7704787bde6f36543d1016,
texto:
{ _id: 'Workflow-2019.02.22-23.21.15-MKRU',
LocalCachePath: 'Z:\\Test\\Cache',
SharedCachePath: [],
Name: 'Test WF',
Desc: 'I\'m testing',
Components: [Array] } } ]
Any insight would be helpful i'm stumbling through this one step at a time.
Here's another query that is giving me results but i guess my issue is going to be to parse out my results as variables.
var query = {'texto.Components.0.Name' : {$gt: ''}}
// var query = {'testo.Name' : {$gt: ''} }
cursor = db.collection("workflows").find(query).toArray(function(err, result) {
if (err) throw err;
Use dot notation (e.g. texto.Name) to query and retrieve fields from nested objects, example:
var query = {'texto.Name': 'Test WF'}
Simply
db.getCollection('TestQueries').find({'texto.Name': 'Test WF'})
Regex used for Case Insensitive.
db.getCollection('TestQueries').find({"texto.Name":{
'$regex' : '^test wa$', '$options' : 'i'
}})
Using collation
db.fruit.createIndex( {"texto.Name": 1},{ collation: {
locale: 'en', strength: 2
} } )
db.getCollection('TestQueries').find(
{ "texto.Name": "test wa" } ).collation( { locale: 'en', strength: 2 }
)
You can also use $elemMatch. It is longer, but allows for multiple fields query.
db.getCollection('TestQueries').find({texto: {$elemMatch: {Name: "test wa"} }))
Official docs here
This question already has answers here:
Why does a GraphQL query return null?
(6 answers)
Closed 3 years ago.
I am learning GraphQL and I have two Object types.
Say, they look like this
Say, The book type looks like this
const BookType = new GraphQLObjectType({
name: 'Book',
fields: () => ({
id: { type: GraphQLID},
name: { type: GraphQLString},
genre: { type: GraphQLString },
author: {
type: authorType,
resolve(parents, args) {
Author.findOne(
{
name: parents.authorName
}, function(err, result) {
console.log(result)
return result
})
}
}
})
})
and Author Type looks like this
const authorType = new GraphQLObjectType({
name: 'author',
fields: () => ({
id: { type: GraphQLID},
name: { type: GraphQLString},
age: { type: GraphQLInt },
books: {
type: new GraphQLList(BookType),
resolve(parent, args) {
}
}
})
})
Now, I am adding data through Mutation (Not sharing it because I think it is irrelevant) and then run query in graphql to add data in Book Type. It correctly displays data for name, genre, id but for authorType it is showing the data as null while the console].log results log something like this in console
//This is console log in terminal
{ age: 'none',
_id: 5bcaf8904b31d50a2148b60d,
name: 'George R Martin',
__v: 0 }
THis is the query I am running in graphiql
mutation{
addBooks(
name: "Game of Thrones",
genre: "Science Friction",
authorName: "George R Martin"
) {
name,
genre,
author {
name
}
}
}
My entire schema is available here
Can someone please-please help me figure out what could I be doing wrong?
A resolver must return either some value or a Promise that will resolve in a value -- if it doesn't the field being resolved will return null. So there's two things off about your code. One, you don't return either a value or a Promise. Two, you return something inside a callback, but that's not actually doing anything, since most libraries disregard the return value of a callback function anyway.
You can wrap a callback in a Promise, but that is going to be overkill here because mongoose already provides a way to return a Promise -- just omit the callback entirely.
resolve(parent, args) {
return Author.findOne({name: parent.authorName)
}
Your mutation resolver works because you return the value returned by calling save(), which actually returns a Promise that will resolve to the value of the model instance being saved.