React: How do I use values from an object's specific key? - javascript

I am new to React and am trying to figure out how to return a particular objects entry by it's key.
So far, I have an object as such:
const questions = [
{
id: '1',
section: 's1',
answers: [
"answer a",
"answer b",
"answer c",
"answer d",
]
},
{
id: '2',
title: 'Question 2',
answers: [
"answer a",
"answer b",
"answer c",
"answer d",
]
},
//etc
which I am currently iterating through and using parts of as props in a component, eg:
return (
<div>
{questions.map((question) => (
<Question
key={question.id}
questionNum={question.id}
title={question.title}
answers={question.answers}
/>
))}
</div>
);
This works fine and as expected.
But now I need to modify this so it only returns the values of 1 given particular key in the object.
I've been searching and experimenting with .get() but to be honest I'm really stumped with how to do this.
Would anyone know the best way to approach this?

You can filter the questions by a particular key of the object first and then do the map. Let's say id with value 1.
return (
<div>
{questions
.filter(({ id }) => id === "1")
.map(question => (
<Question
key={question.id}
questionNum={question.id}
title={question.title}
answers={question.answers}
/>
))}
</div>
)

If I got it right, I guess you can do the same using map itself
Assume you have the below array
const questions = [
{
id: '1',
section: 's1',
answers: [
"answer a",
"answer b",
"answer c",
"answer d",
]
},
{
id: '2',
title: 'Question 2',
answers: [
"answer a",
"answer b",
"answer c",
"answer d",
]
}]
and now you wanna just pull out the answers key alone then you can do something like
const result = questions.map((question) => {answers: question.answers}); // where the specific key here is answers

Related

How can I make a Search String to search like an IN filter on an Array of Object

The filter on UI allows a user to search using the IN criterion. The search string will then become the property of the condition Object.
The search string will look like "1234,5436,8765" and then the condition Object will be like ```
condition: {
field: "Id",
operator: "in",
value: "1234,5436,8765"
}
Now as this is going to be IN filter, so whar criterion should I use so as to make the value search like IN criterion from the results Array.
e.g. for a like filter, I will set my value property like this %1234% so as to search this in the results Array.
Your question isn't clear so try to edit it to make it clearer.
I made a huge assumption here in my answer (as it is not clear from the question):
You could do it with a switch statement and then your various filter methods for each case.
You could do it more robustly, but until the question is clearer, it doesn't make much sense to build this solution out.
const myArrOfObs = [
{Id: 1234, title: "some title 1", other: "some other val 1"},
{Id: 2468, title: "some title 2", other: "some other val 2"},
{Id: 8240, title: "some title 3", other: "some other val 3"},
{Id: 9371, title: "some title 4", other: "some other val 4"},
{Id: 5436, title: "some title 5", other: "some other val 5"},
{Id: 8365, title: "some title 6", other: "some other val 6"},
{Id: 8765, title: "some title 7", other: "some other val 7"},
{Id: 3946, title: "some title 8", other: "some other val 8"}
];
const condition = {
field: "Id",
operator: "in",
value: "1234,5436,8765"
};
function filterArr(arr, cond) {
switch (cond.operator){
case "in":
const valueArr = cond.value.split(',');
return arr.filter(item => valueArr.includes(item[cond.field].toString()));
//case "like":
//return arr.filter( ... );
default:
return null;
}
}
const myFilteredArr = filterArr(myArrOfObs, condition);
console.log(myFilteredArr);

How to get full values in [Array]?

i have a POST request with some Data, i post with Postman , Data like this , But i have some problem is when i console.log(newLesson) i cannot get value in [Array] , but when i try console.log(req.body.quizs) its can !!! Can some one explain to me why ? And how can i get values from that ? Many thanks 😊
"name":"This is name",
"videoId" : "this is videoId",
"level" : "beginner",
"script" : "this is Script",
"quizs" : [
{
"question" : "This is question 1",
"answer" : [
"Answer 1",
"Answer 2",
"Answer 3"
],
"correct_Answer" : "Answer 3"
},
{
"question" : "This is question 2",
"answer" : [
"Answer 1",
"Answer 2",
"Answer 3"
],
"correct_Answer" : "Answer 1"
}
]
}
And this is my backend when received
module.exports.addNewLesson = function(req,res){
let newLesson = {
name : req.body.name,
videoId : req.body.videoId ,
level : req.body.level,
script : req.body.script,
quizs : req.body.quizs
};
console.log(newLesson);
}
And this is what i got
{
name: 'This is name',
videoId: 'this is videoId',
level: 'beginner',
script: 'this is Script',
quizs: [
{
question: 'This is question 1',
answer: [Array],
correct_Answer: 'Answer 3'
},
{
question: 'This is question 2',
answer: [Array],
correct_Answer: 'Answer 1'
}
]
}
How to can i get answer : [Array] ??? Thanks
Try stringifying the output with formatting:
console.log(JSON.stringify(newLesson, null, 4)); // 4 is the number of whitespaces used for formatting

Destructuring an array of objects (es6)

I'm wondering how to destructure an array of objects. I'm attempting to destructure country from the partner array. It is a project requirement that partner be an array of objects, even though there should only ever be one partner country per obj.
arr = [
{ title: "Title A",
desc: "Desc A",
role: {role_desc: "Role Desc A", role_name: "Role A"},
partner: [{country: "Brazil", region: "SA"}]
},
{ title: "Title B",
desc: "Desc B",
role: {role_desc: "Role Desc B", role_name: "Role B"},
partner: [{country: "US", region: "NA"}]
}
]
I am able to populate a table with data for all fields except partner.
arr.map(
({ title, desc, role: {role_name}, partner: [{country}] }) =>
({ title, desc, role: {role_name}, partner: [{country}] })
);
I've referred to Destructure object properties inside array for all elements and Destructuring an array of objects with es6, and it looks like it is not possible to do this without transforming the data first.
Any help would be appreciated (and apologies for the dupe).
You can simply use default value when you want to handle the case when partner is empty array,
const arr = [{ title: "Title A",desc: "Desc A",role: {role_desc: "Role Desc A", role_name: "Role A"},partner: [{country: "Brazil", region: "SA"}]},{ title: "Title B",desc: "Desc B",role: {role_desc: "Role Desc B", role_name: "Role B"},partner: [{country: "US", region: "NA"}]},{ title: "Title C",desc: "Desc C",role: {role_desc: "Role Desc C", role_name: "Role C"},partner: []}]
const final = arr.map(
({ title, desc, role: {role_name}, partner}) =>
({ title, desc, role: {role_name}, partner:[ {country} = {country: undefined } ] })
);
console.log(final)
That being said we should keep our code as readable as possible, here it becomes so hard on eyes instead of trying to save one extra line, we should opt for making it more readable
const arr = [{ title: "Title A",desc: "Desc A",role: {role_desc: "Role Desc A", role_name: "Role A"},partner: [{country: "Brazil", region: "SA"}]},{ title: "Title B",desc: "Desc B",role: {role_desc: "Role Desc B", role_name: "Role B"},partner: [{country: "US", region: "NA"}]},{ title: "Title C",desc: "Desc C",role: {role_desc: "Role Desc C", role_name: "Role C"},partner: []}]
const final = arr.map(
({ title, desc, role: {role_name}, partner}) => {
let country = partner[0] && partner[0].country || undefined
return { title, desc, role: {role_name}, partner:[ {country}] }
}
);
console.log(final)
I was overlooking a very simple answer due to an equally simple error:
arr.map(
({ title, desc, role: {role_name}, partner}) =>
({ title, desc, role: {role_name}, partner: (partner[0] && partner[0].country) || 'Undefined' })
);
Every item in the array did not necessarily have a "country" property. For certain items, partner is just an empty array. The above fixed the issue.
I agree that it doesn't make sense to make partner an array if it will only ever contain one object. Client requirements, however.

How To Delete Mongo Object (nested 2 arrays down) without knowing its position?

I need to remove one of the 'answers' objects nested in the Doc below. I have the text of the answer I'm looking for. I don't have the index of the question OR the answer that I need to drill down into the arrays.
For example, I know that the text of the question I'm trying to drill down into is "This is a question." and the answer I want to delete is "Answer One".
How would you go about doing that?
Here's the sample MongoDB Doc:
(Quizzes have Questions; Questions have Answers)
{
name: "Sample Quiz",
categories: [
{ name: "testcategory1", description: "this is a test category" }
,{ name: "categoryTWO", description: "the second category" }
],
questions: [
{ text: "This is a question."
,answers: [
{text: "Answer One", affected_categories: "testcategory1"}
,{text: "Answer Two", affected_categories: "testcategory1"}
,{text: "Answer Three", affected_categories: "categoryTWO"}
]
}
,{ text: "This is the second question."
,answers: [
{text: "Mepho One", affected_categories: "testcategory1"}
,{text: "Answer Toodlydoo", affected_categories: "testcategory1"}
,{text: "Lehmen Sumtin", affected_categories: "categoryTWO"}
]
}
],
}
When I was deleting an item that was nested a single level down (in this case, a question), I was able to do it with a query like:
Quizzes.update(
{ _id: quizID, 'questions.text': questionText },
{ $pull: { questions: {text: questionText }}}
);
(as described here: http://docs.mongodb.org/manual/core/update/#Updating-ModifierOperations , in the section titled "Update an Element without Specifying Its Position")
I tried expanding that to something like:
Quizzes.update(
{ _id: quizID, 'answers.text': answerText },
{ $pull: { questions: {text: questionText {answers: {text: answerText }}}}}
);
but didn't have any luck.
Any ideas would be greatly appreciated.
Use the positional operator in combination with $pull condition:
> db.quizzes.update(
{_id:<quizID>, "questions.text":"This is the second question."},
{$pull:{ "questions.$.answers":{"text":"Answer Toodlydoo"}}}
);
The above works to remove the second answer from the second question.

sorting selected items in an array (javascript)

I have got an array that contains data in hierarchical form such as:
Level 2
chapter 1
chapter 2
Level 4
chapter 1
chapter 2
Level 1
chapter 1
chapter 2
Level 3
chapter 1
chapter 2
If I just call array.sort(), the hierarchy gets disturbed. So, I have to develop my own way of sorting items. The thing I can't understand is, how would I compare two levels such that I would know that level 1 is less than level 2 and it should be at the top index of the array?
You really shouldn't be using a flat array. You lose all the hierarchical information. Something like this would be better:
//I've deliberately made these unsorted to show you that sorting works
levels = ["Level 4", "Level 3", "Level 1", "Level 2"];
data = {
"Level 3" : ["chapter 1", "chapter 2"],
"Level 1" : ["chapter 2", "chapter 1"],
"Level 2" : ["chapter 2", "chapter 1"],
"Level 4" : ["chapter 1", "chapter 2"]
};
levels.sort();
for(var i = 0 i < levels.length; i++) {
console.log(levels[i]);
var chapters = data[levels[i]];
chapters.sort();
for(var j = 0; j < chapters.length; j++) {
console.log(chapters[j]);
}
}
EDIT
Rob suggested using levels.sort(function(x,y){return x.localeCompare(y)}) instead of the regular .sort(). The former will sort ["abc", "Abcd", "Ab"] to ["Ab", "abc", "Abcd"] instead of ["Ab", "Abcd", "abc"].
This should reformat the flat PHP array to the nicer JS object:
var fromPHP = ['Level 2','chapter 1','chapter 2','Level 4','chapter 1','chapter 2','Level 1','chapter 1','chapter 2','Level 3','chapter 1','chapter 2'];
var levels = [],
betterArray = [fromPHP[0]],
currentLevel=betterArray[0];
for (var i=1;i<fromPHP.length;i++) {
if (fromPHP[i].substr(0,5) == 'Level') {
currentLevel = [];
levels.push(fromPHP[i]);
betterArray[fromPHP[i]] = currentLevel;
} else {
currentLevel.push(fromPHP[i]);
}
}
Should give the following levels and betterArray:
// levels:
['Level 4','Level 3','Level 1','Level 2']
// betterArray:
{
'Level 2': ['chapter 1','chapter 2'],
'Level 4': ['chapter 1','chapter 2'],
'Level 1': ['chapter 1','chapter 2'],
'Level 3': ['chapter 1','chapter 2']
}
Now you can run whatever sorting you want on the subarrays and get what you wanted.

Categories

Resources