Suppose i have a array like this:
const HeaderData = [
{
header: {
title: "How you'll benefit",
detail:
"We create this goals to help you recover from your recent surgery. Slowly increase your physical strength is an important part of recovery. With this plan, you will be back to normal in no time. You got this!",
},
xyz: {
title: "dsdsdas",
},
},
{
mainData: [
{
detail: "4/1/2021",
},
{
detail: "Jennifer. 0",
},
{
detail: "4/1/2021",
},
{
detail: "In progress",
},
],
},
{
activity: [
// title
{
activity1: "Take the stairs",
activity2: "5 Sets of Sit-Ups",
activity3: "3 sets of Push-Up",
activity4: "Weight-lifting",
},
// notSatisfied
{
activity1: 5,
activity2: 3,
activity3: 7,
activity4: 3
},
//neutral
{
activity1: 0,
activity2: 2,
activity3: 2,
activity4: 3,
},
//satisfied
{
activity1: 2,
activity2: 5,
activity3: 1,
activity4: 0,
},
],
},
]
I only know how to get data in a child if they have same name, for example in my array is activity1 or title, using map() because it have the same name, but problem is , they very confusing and easy to misunderstand ,if i want to get all data in a child , how can i do that. For example, if i change above array to this
const HeaderData = [
{
header: {
title: "How you'll benefit",
detail:
"We create this goals to help you recover from your recent surgery. Slowly increase your physical strength is an important part of recovery. With this plan, you will be back to normal in no time. You got this!",
},
xyz: {
title: "dsdsdas",
},
},
{
mainData: [
{
title: "Created On",
detail: "4/1/2021",
},
{
title: "Created By",
detail: "Jennifer. 0",
},
{
title: "Started",
detail: "4/1/2021",
},
{
title: "Completed",
detail: "In progress",
},
],
},
{
activityName: [
{
title: "Take the stairs",
notSatisfied: 5,
neutral: 0,
satisfied: 2,
},
{
title: "5 Sets of Sit-Ups",
notSatisfied: 3,
neutral: 2,
satisfied: 5,
},
{
title: "3 sets of Push-Up",
notSatisfied: 7,
neutral: 3,
satisfied: 1,
},
{
title: "Weight-lifting",
notSatisfied: 3,
neutral: 2,
satisfied: 0,
},
],
},
]
It much more clear now, in my opinion but now i'm stuck, i don't khow how to get data from first elemet from mainData
{
title: "Take the stairs",
notSatisfied: 5,
neutral: 0,
satisfied: 2,
},
If i want to get ALL this data at once through map(), how can i do that? I only know if they have the same name
Please help, thank a lot
Hoping this is what you are looking for:
HeaderData.map(elem => {if(elem.activityName){console.log(elem.activityName[0])}})
Related
Is there a way to boost score for exact match in Atlas search?
I'm having issues getting the right/best translation for 'hi' from English to French. After some debugging I discovered that the first three(3) documents returned from my aggregation has the same score of '2.362138271331787' each.
I'm expecting 'hi' to have a higher score since it has an exact match with the same search query, but 'it’s his' and 'his' seems to have the same score with 'hi'.
Here's my search query:
const searchOption= [
{
$search: {
text: {
query: 'hi',
path: 'english',
},
},
},
{ $project: { _id: 0, french: 1, english: 1, score: { $meta: "searchScore" } } },
{ $limit: 5 },
];
const result = await Greetings.aggregate(searchOption, { cursor: { batchSize: 5 } }).toArray();
Here's are the documents returned. The list is ordered by search score:
[
{
"english": "it’s his",
"french": "c'est le sien",
"score": 2.362138271331787
},
{
"english": "hi",
"french": "salut",
"score": 2.362138271331787
},
{
"english": "his",
"french": "le sien",
"score": 2.362138271331787
},
{
"english": "it’s his failure to arrange his",
"french": "c'est son incapacité à organiser son",
"score": 2.2482824325561523
},
{
"english": "it’s his failure to arrange his time",
"french": "c'est son incapacité à organiser son temps",
"score": 2.0995540618896484
}
]
The score is a "relevance score" implemented internally by Mongo, I will say it is surprising to me that field length is not part of the score even if it's a "text" operand, I would personally expect it to be added in some form in the near future.
For now you could use a workaround to construct the score you want, for example you could use a should (or) expressions with a phrase operator combined with a boost score function, like so:
const searchOption= [
{
$search: {
"compound": {
"should" : [
{
"phrase":{
"query": "hi",
"path": "english",
"score": {"boost":{"value":5}}
}
},
{
text: {
query: 'hi',
path: 'english',
},
},
]
}
}
},
{ $project: { _id: 0, french: 1, english: 1, score: { $meta: "searchScore" } } },
{ $limit: 5 },
];
const result = await Greetings.aggregate(searchOption, { cursor: { batchSize: 5 } }).toArray();
Otherwise you could also just sort by english length combined with the score ( this is under the assumptions scores will be tied), obviously this is not a real sort as it assumes the top 5 results are the actual top 5 results you're expecting to get.
const searchOption= [
{
$search: {
text: {
query: 'hi',
path: 'english',
},
},
},
{ $project: { _id: 0, french: 1, english: 1, score: { $meta: "searchScore" }, len: {$strLenCP: "$english"} } },
{ $sort : { score: -1, len: -1 } },
{ $limit: 5 },
];
const result = await Greetings.aggregate(searchOption, { cursor: { batchSize: 5 } }).toArray();
This is a known limitation of Atlas Search and the solution is mentioned here:
https://www.mongodb.com/docs/atlas/atlas-search/autocomplete/#limitations
The lucene.keyword analyzer on a string type is so helpful for exact matches in scenarios where score fidelity is essential.
Basically, the path english should be defined in the index definition as both autocomplete and string, like:
[
{"type": "string"},
{"type": "autocomplete"}
]
The above assumes that you are not using a language analyzer for autocomplete or string, which is probably not ideal for string.
Then, on the query side, you want a compound query where both options are should clauses. You should boost the text clause and not the autocomplete clause.
I have two dropdowns - where each dropdown should filter an objects key. The dropdowns should not exclude each other, or both values from dropdown should work indenpentedly from each other (ie both dropdown values does not need to be true for filtering).
When I select an item from the dropdown, I get one array with two objects, for each dropdown:
[
{
"name": "Type",
"value": [
"calibration"
],
"selected": [
{
"text": "calibration"
}
]
},
{
"name": "Function group",
"value": [
"1 - Test",
"2 - Programming"
],
"selected": [
{
"text": "1 - Test"
}
]
}
]
Above shows two objects, for the two different dropdowns - one with name "type" and one with "Function group".
The "value" in the object above is all of the dropdown items.
"selected" holds the selected item from the dropdown and the filtering should be based on that.In this case we have selected "calibration" and "Test".
The "type" dropdown should filter on the data "category" field while the "function group" should filter on "groupDescription" field. The data that needs to be filtered based on the mentioned keyes and selected values looks like this:
const mockData = [
{
operationDetails: {
id: '5119-03-03-05',
number: '41126-3',
description: 'Clutch wear, check. VCADS Pro operation',
category: 'calibration', //type dropdown
languageCode: 'en',
countryCode: 'GB'
},
functionDetails: {
groupId: 411,
groupDescription: 'Test', //function group dropdown
languageCode: '',
countryCode: ''
},
lastPerformed: '2021-02-22',
time: 20,
isFavorite: false
}
,
{
operationDetails: {
id: '5229-03-03-05',
number: '41126-3',
description: 'Defective brake pad',
category: 'calibration', ///type dropdown
languageCode: 'en',
countryCode: 'GB'
},
functionDetails: {
groupId: 411,
groupDescription: 'Programming', //function group dropdown
languageCode: '',
countryCode: ''
},
lastPerformed: '2020-01-22',
time: 20,
isFavorite: false
}
]
Playground with mock data and response example from dropdown here.
How to filter the data based on the values from the dropdown objects, for each key its responsible for?
It's not the prettiest code, but it does work. The one thing that you'd want to watch out for is the regex. It would be better to not have to parse and do a straight match like category, but if your cases are static then you should be able to figure out if this will work every time. It would also be nice to have a field key in filterDetails so you know which field to try to match in the actual data and you could program that in.
const filterDetails = [
{
name: "Type",
value: ["calibration"],
selected: [
{
text: "calibration",
},
],
},
{
name: "Function group",
value: ["1 - Test", "2 - Programming"],
selected: [
{
text: "Test",
},
],
},
];
const mockData = [
{
operationDetails: {
id: "5119-03-03-05",
number: "41126-3",
description: "Clutch wear, check. VCADS Pro operation",
category: "calibration", //type
languageCode: "en",
countryCode: "GB",
},
functionDetails: {
groupId: 411,
groupDescription: "Test", //function group
languageCode: "",
countryCode: "",
},
lastPerformed: "2021-02-22",
time: 20,
isFavorite: false,
},
{
operationDetails: {
id: "5229-03-03-05",
number: "41126-3",
description: "Defective brake pad",
category: "calibration", ///type
languageCode: "en",
countryCode: "GB",
},
functionDetails: {
groupId: 411,
groupDescription: "Programming", //function group
languageCode: "",
countryCode: "",
},
lastPerformed: "2020-01-22",
time: 20,
isFavorite: false,
},
];
console.log(
"filtered mockData: ",
mockData.filter(({ operationDetails, functionDetails }) => {
let groupDescriptionMatch = false;
let categoryMatch = false;
for (const details of filterDetails) {
if (
details.name === "Type" &&
details.selected[0].text === operationDetails.category
)
categoryMatch = true;
if (details.name === "Function group") {
let parsedGroup = details.selected[0].text.match(/[a-zA-Z]+/g);
if (parsedGroup[0] === functionDetails.groupDescription) {
groupDescriptionMatch = true;
}
}
}
return groupDescriptionMatch && categoryMatch;
})
);
For Example
Suppose that using the models below, there is one task, t.
I would like to create a sequence for doing task t twice. In the database, this is represented by two rows in the taskSequences with unique ids and different sequence numbers.
However, when I try to use sequelize to retrieve the sequence and its tasks using this query:
models.sequence.findByPk(1, {include: [{model: models.task}]})
, the result only contains one of the tasks.
Is this a limitation of sequelize, or am I missing something?
Models
Sequence Model
const sequence = sequelize.define('sequence', {
name: DataTypes.STRING
}, {});
sequence.associate = function(models) {
sequence.belongsToMany(models.task, {
through: models.taskSequence,
foreignKey: "sequence_id",
otherKey: "task_id"
}
}
Task Model
const task = sequelize.define('task', {
name: DataTypes.STRING
}, {});
sequence.associate = function(models) {}
TaskSequence Model
const taskSequence= sequelize.define('taskSequence', {
sequenceNumber: DataTypes.INTEGER,
task_id: DataTypes.INTEGER,
sequence_id: DataTypes.INTEGER
}, {});
sequence.associate = function(models) {
taskSequence.belongsTo(models.task, {foreignKey: "task_id"});
taskSequence.belongsTo(models.sequence, {foreignKey: "sequence_id"});
}
Output
Expected
{
"id": 1,
"name": "Example Sequence",
"tasks": [
{
"id": 1,
"name": "Example Task",
"taskSequence": {
"sequenceNumber": 1,
"task_id": 1,
"sequence_id": 1,
}
},
{
"id": 1,
"name": "Example Task",
"taskSequence": {
"sequenceNumber": 2,
"task_id": 1,
"sequence_id": 1,
}
}
]
}
What I'm getting
{
"id": 1,
"name": "Example Sequence",
"tasks": [
{
"id": 1,
"name": "Example Task",
"taskSequence": {
"sequenceNumber": 2,
"task_id": 1,
"sequence_id": 1,
}
}
]
}
Yes, it is a limitation of Sequelize. It filters out duplicates by default. You should be able to workaround it like this:
models.sequence.findByPk(1, {
include: [{
model: models.taskSequence,
include: [{
model: models.task,
}]
}]
})
The downside is that the returned data structure will be different from what you want initially
Hello guys I have two objects
Questions
[
0:{
question:"favourite food", id:"1", question_type:"text",
sub_questions: {
0:{
question:"what is it's origin", parent_id:"1",
sub_question_id:"1" question_type:"text",
},
1:{
question:"how much does it cost", parent_id:"1",
sub_question_id:"2" question_type:"text",
}
}
},
1:{
question:"Dream car", id:"2", question_type:"text"
},
2:{
question:"favourite pet", id:"2", question_type:"text"
}
]
Answers
[
0:{
question_id:1, response: "Fufu", sub_question: false
},
1:{
parent_id:1, question_id:1, response: "Fufu originated from West Africa", sub_question: true
},
2:{
parent_id:1, question_id:2, response: "USD3", sub_question: true
},
3:{
question_id:3, response: "Tesla Model S", sub_question: false
}
4:{
question_id:3, response: "Cat (Nameless)", sub_question: false
}
]
I want to be able to append the answers to the right question fields (including the sub-questions)
Please all suggestions are welcomed and thanks in advance for helping, please note that I need the answer in pure javascript, no jquery
It would seem you will have to iterate through the questions array, and the attached sub_questions arrays, with array.prototype.forEach function and then using array.prototype.find function for each of item to find and attach a matching answer.
Please find the solution implemented in this link:
https://jsfiddle.net/jawLtz03/
var questions = [{
question: "favourite food",
id: "1",
question_type: "text",
sub_questions: [{
question: "what is it's origin",
parent_id: "1",
sub_question_id: "1",
question_type: "text",
},
{
question: "how much does it cost",
parent_id: "1",
sub_question_id: "2",
question_type: "text",
}
]
},
{
question: "Dream car",
id: "3",
question_type: "text"
},
{
question: "favourite pet",
id: "4",
question_type: "text"
}
];
var answers = [{
question_id: 1,
response: "Fufu",
sub_question: false
},
{
parent_id: 1,
question_id: 1,
response: "Fufu originated from West Africa",
sub_question: true
},
{
parent_id: 1,
question_id: 2,
response: "USD3",
sub_question: true
},
{
question_id: 3,
response: "Tesla Model S",
sub_question: false
},
{
question_id: 4,
response: "Cat (Nameless)",
sub_question: false
}
];
var innerHtml = "<ul>"
questions.forEach(function(question, index) {
innerHtml += `<li>Question ${index + 1}. ${question.question}?<br/>`;
const hasSub = question.sub_questions ? true : false;
question.answer = matchWithAnswer(question, false);
innerHtml += `Answer: ${question.answer.response}.`;
if (hasSub) {
innerHtml += "<p><ul>";
question.sub_questions.forEach(function(sub_question, sub_index) {
innerHtml += `<li>Sub-Question ${sub_index + 1}. ${sub_question.question}?<br/>`;
sub_question.answer = matchWithAnswer(sub_question, true);
innerHtml += `Answer: ${sub_question.answer.response}.</li>`;
});
innerHtml += "</ul></p>";
}
innerHtml += "</li>";
});
function matchWithAnswer(question, isSub = false) {
return answers.find(function(answer) {
if (isSub) {
return answer.sub_question == true && answer.parent_id == question.parent_id && answer.question_id == question.sub_question_id;
} else {
return answer.question_id == question.id;
}
});
}
innerHtml += "</ul>";
var div = document.getElementById('output');
div.innerHTML = innerHtml;
<h1>Q & A</h1>
<div id="output"></div>
Hello im trying to append the media size for my image set so the first image should have the mediaSize 768px the second 1024 and so on, how can i wrap it up. i would like to use the values for my srcset : to set the min width for media.
here is my Object
data = {[
{
thumbnail: 'http://via.placeholder.com/90x90',
images:
[
'http://via.placeholder.com/768x400',
'http://via.placeholder.com/1024x400',
'http://via.placeholder.com/1999x400',
{mediaSize : [ "768px", "1024px","1999px "]}
]
}
]}
var data = [
{
'thumbnail': 'http://via.placeholder.com/90x90',
'images':
[
{ 'link': 'http://via.placeholder.com/768x400' },
{ 'link1': 'http://via.placeholder.com/1024x400' },
{ 'link2': 'http://via.placeholder.com/1999x400' },
{
'mediaSize': [
{ 'id': "768px" },
{ 'id1': "1024px" },
{ 'id2': "1999px" },
]
},
]
}
]
check this....
var data = [
{
"CategoryID": 1,
"CategoryName": "Soler Power Plant",
"CategoryProducts": [
{
"ID": 1,
"Name": 'Commercial Solar Power Plant',
"SubTitle": 'Eco, Eco Friendly, Energy, Green, Solar',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": 'Having a pre-determined quality administration system, we are thoroughly involved in delivering Commercial Solar Power Plant.',
"ImageUrl": 'assets/images/Products/Sola-power-plant.jpg',
}]
}]