const book1 = this.state.books[0]; //giving one book
console.log(book1); //output->{id: 1, bookname: "Physics", price: 600, author: "ABC", pages: 567, …}
const {id,bookname,price,author,pages,category} = {book1};
console.log(price); //output->undefined
I have already tried a lot of things. How To get the value of particular property?
Here is the JSON file:
[
{
"id": 1,
"bookname": "Physics",
"price": 600,
"author": "ABC",
"pages": 567,
"category" : "Science"
}
]
The JavaScript object destructuring shown is invalid, because of the curly braces around book1.
Remove those braces:
const { id, bookname, price, author, pages, category } = book1;
Here's a simpler example:
> const book = { price: 600 }
undefined
> const { price } = book
undefined
> price
600
Yes, as Jake mentioned, what you're trying to do here is called destructuring assignment. So as per the correct syntax,
const { id, bookname, price, author, pages, category } = book1;
this would actually mean,
const id=book1.id
const bookname=book1.bookname
And so on. You could have a look at https://javascript.info/destructuring-assignment for more information on destructuring assignment.
Related
I'm trying to filter the json data. There is a field called "brand" in my json (so basically I'm trying to filter the data by brands)
This is how my json looks
{
"items": [
{
"_id": "30baa1ca-4186-4ff0-abe8-a5970e753444",
"_owner": "1d3480e5-0eda-47ef-8406-38d89bf15ded",
"_createdDate": "2022-05-09T08:47:29.137Z",
"discountedPrice": "44.97",
"_updatedDate": "2022-05-09T08:48:44.147Z",
"getDealLink": "https://amzn.to/3FqBq4O",
"brands": [
"Amazon"
],
"title": "Mellanni Extra Deep Pocket Twin XL Sheet Set ",
"amazonlogo": "wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346",
"save": "#1 Best Seller",
"link-items-all": "/items/",
"link-items-title": "/items/mellanni-extra-deep-pocket-twin-xl-sheet-set-"
},
{
"_id": "a7d3aaa8-9654-4535-b6c5-b147ff0d8eb3",
"_owner": "1d3480e5-0eda-47ef-8406-38d89bf15ded",
"_createdDate": "2022-05-08T22:35:38.398Z",
"discountedPrice": "$81.59",
"_updatedDate": "2022-05-08T22:39:52.801Z",
"getDealLink": "https://amzn.to/3ymXGLe",
"brands": [
"Amazon"
],
"originalPrice": "$199.99",
"title": "2 Pack Stadium chairs for bleachers with back support",
"amazonlogo": "wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346",
"link-items-all": "/items/",
"link-items-title": "/items/2-pack-stadium-chairs-for-bleachers-with-back-support"
},
and this is my dart code
void getAmazon() async {
var response = await http.get(Uri.parse(url));
var decodeResponse = jsonDecode(response.body);
List data = decodeResponse['items'] as List;
Iterable filteredData = data.where((element) => element['brands'][0] == 'Amazon');
print(filteredData); // returns nothing
}
it doesn't return/print anything. What am I doing wrong?
Better to use contains to check if a brand is listed. Also check if "brands" field is available for better stability.
final filteredData = data.where((element) => (element['brands'] != null ? element['brands'].contains('Amazon') : false));
In your code, you are checking if brands it's equal to Amazon, but brands is actually a List. (Or in the case you are checking on a particular index, this could change)
So ["Amazon"] ≠ Amazon.
In the code below you will now check if brands contains "Amazon".
Iterable filteredData = data.where((element) => element['brands'].contains('Amazon'));
void getAmazon() async {
var response = await http.get(Uri.parse('https://mockbin.org/bin/e123b53d-6e35-49e7-a94e-f49554a63d7e'));
var decodeResponse = jsonDecode(response.body);
List data = decodeResponse['items'] as List;
Iterable filteredData = data.where((element) => element['brands'][0] == 'Amazon');
log('ddf ${filteredData}'); // returns nothing
}
I had added third product as brand from flipkart it filter this!
you can check this url https://mockbin.org/bin/e123b53d-6e35-49e7-a94e-f49554a63d7e
Your code actually works as expected!!!
[log] ddf ({_id: 30baa1ca-4186-4ff0-abe8-a5970e753444, _owner: 1d3480e5-0eda-47ef-8406-38d89bf15ded, _createdDate: 2022-05-09T08:47:29.137Z, discountedPrice: 44.97, _updatedDate: 2022-05-09T08:48:44.147Z, getDealLink: https://amzn.to/3FqBq4O, brands: [Amazon], title: Mellanni Extra Deep Pocket Twin XL Sheet Set , amazonlogo: wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346, save: #1 Best Seller, link-items-all: /items/, link-items-title: /items/mellanni-extra-deep-pocket-twin-xl-sheet-set-}, {_id: a7d3aaa8-9654-4535-b6c5-b147ff0d8eb3, _owner: 1d3480e5-0eda-47ef-8406-38d89bf15ded, _createdDate: 2022-05-08T22:35:38.398Z, discountedPrice: $81.59, _updatedDate: 2022-05-08T22:39:52.801Z, getDealLink: https://amzn.to/3ymXGLe, brands: [Amazon], originalPrice: $199.99, title: 2 Pack Stadium chairs for bleachers with back support, amazonlogo: wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346, link-items-all: /items/, link-items-title: /items/2-pack-stadium-chairs-for-bleachers-with-back-support})
I am new to typescript in angular 2 and i stuck with a situation.
I have a json array in this format
needle json
[{"empId":100,"orgId":500}
{"empId":201,"orgId":566}]
The above json is in a particular order and we need to keep that order maintained while looking for those in another json array(Haystack)
Haystack json array
[
{"empCode":21,"fname":"Ashish","Lname":"Shukla"},
{"empCode":22,"fname":"John","Lname":"Mark"},
{"empCode":21,"fname":"Vigil","Lname":"Rocker"},
{"empCode":201,"fname":"Rick","Lname":"Mandez"},
{"empCode":21,"fname":"Erik","Lname":"Francis"},
{"empCode":100,"fname":"Alex","Lname":"Mishra"},
{"empCode":21,"fname":"Feeder","Lname":"Kapoor"},
{"empCode":21,"fname":"Dan","Lname":"Rox"},
{"empCode":21,"fname":"Herb","Lname":"Deen"},
{"empCode":21,"fname":"Nate","Lname":"Diaz"},
{"empCode":21,"fname":"Nick","Lname":"Diaz"},
{"empCode":21,"fname":"Conor","Lname":"Pussy"}
]
Now i need to get those values from haystack array whose id matches in needle keeping the order maintained of the needle
{"empCode":100,"fname":"Alex","Lname":"Mishra"},
{"empCode":201,"fname":"Rick","Lname":"Mandez"}
I have achieved the solution to this problem but i guess my solution is not optimal as i am using many loops. Can some one suggest me a good solution.
PLS NOTE: Order of the employee id should be maintained in result json as of the needle json.
Thanks a lot :)
This should work
public needle: any;
public hayStack: any;
this.needle = [
{"empId": 100, "orgId": 500},
{"empId": 201, "orgId": 566}
];
this.hayStack = [
{"empCode":21,"fname":"Ashish","Lname":"Shukla"},
{"empCode":22,"fname":"John","Lname":"Mark"},
{"empCode":21,"fname":"Vigil","Lname":"Rocker"},
{"empCode":201,"fname":"Rick","Lname":"Mandez"},
{"empCode":21,"fname":"Erik","Lname":"Francis"},
{"empCode":100,"fname":"Alex","Lname":"Mishra"},
{"empCode":21,"fname":"Feeder","Lname":"Kapoor"},
{"empCode":21,"fname":"Dan","Lname":"Rox"},
{"empCode":21,"fname":"Herb","Lname":"Deen"},
{"empCode":21,"fname":"Nate","Lname":"Diaz"},
{"empCode":21,"fname":"Nick","Lname":"Diaz"},
{"empCode":21,"fname":"Conor","Lname":"Pussy"}
];
const needleEmpId = this.needle.map(item => item.empId);
const hayStackEmpCode = this.hayStack.map(item => item.empCode);
const result = hayStackEmpCode.map((id, index) => {
if (needleEmpId.indexOf(id) != -1) {
return this.hayStack[index];
}
}).sort().filter(item => (item != undefined));
console.log(result);
Result
0:{empCode: 100, fname: "Alex", Lname: "Mishra"}
1:{empCode: 201, fname: "Rick", Lname: "Mandez"}
Situation
In a project I have this code to select data from a table. Please note, it is working, I only don't get the result I expect.
serviceSurveyQuestions.find({
query: {
survey_id: this.survey_id,
user_id: this.$store.state.auth.user.id, //TODO move this to the hook!!
//todo make satus also not equal new
$or: [
{ status_id: process.env.mfp.statusSurveyQuestionStarted },
{ status_id: process.env.mfp.statusSurveyQuestionPlanned }
],
$sort: {
survey_question_question: 1
},
$limit: 150,
$select: [
'survey_question_question',
'survey_question_at',
'survey_question_answer',
'survey_question_details',
'survey_question_source_id',
'survey_question_source_answer_id',
'survey_question_source_user_id',
'survey_question_step',
'survey_question_dep_step',
'id'
]
}
}).then(page => {
this.listSurveyQuestions = page;
});
When I see what would be in one item of listSurveyQuestion I will see this:
{
"survey_question_question": "PEN 10 Scope vaststellen",
"survey_question_at": "2017-06-23T06:46:10.038Z",
"survey_question_answer": "",
"survey_question_details": "tester done",
"survey_question_source_id": 83499707,
"survey_question_source_answer_id": 74864,
"survey_question_source_user_id": 83488216,
"survey_question_step": 10,
"survey_question_dep_step": null,
"id": 4651,
"source_user": {
"user_id": 1005
},
"status": {
"status": "Planned"
},
"language": {
"language": "Dutch"
,
"source": {
"source": "MexonInControl - Pob - Dev (local)"
},
"survey_question": [{
"answer_type_id": 1014,
"answer_en": null,
"answer_nl": null,
"answer_explanation_en": null,
"answer_explanation_nl": null,
"survey_question_next_id": 4652
} ]
}
I know the result is comming from the configuration in my get and find hook of the service being called.
Expected Result
What I expect to happen is that the data returned is only the columns defined in the $SELECT. If I leave this as is, it will work but I'm getting to much data from the database which can be seen later as a security breach. Not with this example, but with other tables it will.
** Question **
So what do I need to change to have this functioning as expected. You could adapt the return of the service, but then I can't use the same service in other situations for the columns aren't available. Or can you pass an option to the service which will result in if (parameter = view 1) then return view 1 and so on.
** Solving **
Remark 1:
So I just see the 'cause' is a bit different. The configured hooks returns more columns from the question table which are not shown. So my guess here is that if you don't configure the includes in the find query, it will pass all includes. I need to check that and if this is the case, see if there is a option to not select the 'includes' as well.
Assuming that the hook you are referring to is setting hook.params.sequelize similar to this answer you will have to check if you included properties are also set in the $select query with something like this:
// GET /my-service?include=1
function (hook) {
const include = [];
const select = hook.params.query.$select;
// Go through all properties that are added via includes
['includeProp1', 'includeProp2'].forEach(propertyName => {
// If no $select or the include property is part of the $select
if(!select || select.indexOf(propertyName) !== -1) {
include.push({ model: ModelForIncludeProp1 });
}
});
hook.params.sequelize = { include };
return Promise.resolve(hook);
}
I'm trying to implement a filter based on the answer to this question, but it isn't working for me. For code:
function MyCtrl($scope, $timeout)
{
$scope.tweets = [
{
created_at: "Date",
text: "tweet text",
users:
[
{
name: "user name",
screen_name: "user screen name",
profile_image_url: "profile pic"
},
{
name: "user name 2",
screen_name: "user screen name 2",
profile_image_url: "profile pic"
}
]
},
{
created_at: "Date",
text: "tweet text 2",
users:
[
{
name: "user name",
screen_name: "user screen name",
profile_image_url: "profile pic"
},
{
name: "user name 2",
screen_name: "user screen name 2",
profile_image_url: "profile pic"
}
]
},
{
created_at: "Date",
text: "tweet text 3",
users:
[
{
name: "user name",
screen_name: "user screen name",
profile_image_url: "profile pic"
},
{
name: "user name 2",
screen_name: "user screen name 2",
profile_image_url: "profile pic"
}
]
}
];
}
and the template:
<div ng-app ng-controller="MyCtrl">
<div ng-repeat="tweet in tweets">
for each tweet, user 2's name should be printed here >>
{{(tweet.users | filter:{screen_name:'user screen name 2'}).name}}
_____________________________________
</div>
</div>
I'm seeing output of:
for each tweet, user 2's name should be printed here >>
for each tweet, user 2's name should be printed here >>
for each tweet, user 2's name should be printed here >>
I would expect that "user name 2" would be printed out after each ">>". I don't know why that filter isn't working on an array of each iterated element. Thanks.
fiddle
The filter doesn't return a user. It returns an array of users matching the filter condition. So in that case, an array containing one user.
So it should be
{{(tweet.users | filter:{screen_name:'user screen name 2'})[0].name}}
You could have found this yourself easily by just using
{{ (tweet.users | filter:{screen_name:'user screen name 2'}) }}
to see what the result of the filter was.
AND IF THE SAME USER IS MORE THAN ONCE ON THE SAME MESSAGE?
If you have more than one message from one user, the above answer will not work and, instead, will display something strange.
In order to better filter your data, you should try to use filter functions when you have nested objects or arrays inside objects and arrays. I had a similar problem in this question: Filtering data with AngularJS Filter. How to iterate over objects?
So, to your question!
First, you need to go one level above to apply the filter to all the objects. Using the filter where you are, you can't see the big picture and act according. The tack by is being used because ng-repeat can't have duplicated values in a array.
<div ng-app='app' ng-controller="MyCtrl">
<div ng-repeat="tweet in tweets | custom track by $index">
for each tweet, user 2's name should be printed here >>
{{ tweet }}
_____________________________________
</div>
</div>
Now, this is the important part. I'm registering a angular.module as app just because I prefer this way. After that, I create a filter called custom that was acessed in the html code.
var app = angular.module('app', []);
I've changed a little your code, So I can see it better in my way:
app.controller('MyCtrl', function ($scope, $timeout){...});
app.filter('custom', function () {
return function (tweets) {
var formatted = []; //Initialize array to be returned.
for (var j = 0; j < tweets.length; j++) { //Iterate over all tweets.
var tweet = tweets[j]; //Select a single tweet.
//Above, iterate over all users on a tweet.
for (var i = 0; i < tweet.users.length; i++) {
var user = tweet.users[i]; //Select a single user of the tweet.
if (tweet.user[i].screen_name == 'user screen name 2'){
//If match what you want, insert it in the array to be returned.
formatted.push(tweet.user[i].name);
};
};
};
return formatted; //Return the array.
};
});
And, finally, if you want to test, here are a fully function jsfiddle with your own code. :)
Query is your string and filter my query like name present in json list
ng-repeat="tweet in tweets" | filter: { users: query }
I have two question on basic REST concepts.
QUESTION 1: Categories
So I have a list of Categories I want to show from a database.
SELECT * from categories
Currently, I use this REST desgin: /api/v1/categories/
Is that proper?
I have also seen /api/v1/categories/list/ -- or is this preferred? (If so, then what would a simple /categories call display then? (Or would the proper way then be /api/v1/category/list where category is singular and adding list will show you all categories -- this way a call to /category would allow veiwing info on just one?)
QUESTION 2: Subcategories. (Think "Seinfeld" as a subcategory of "Television".)
SELECT * FROM subcategories" WHERE category_id = {id}
The id above might be the Television Category where I want to get specific shows listed.
Would I do /api/v1/categories/{id}/ for the Subcategory with the subcat_id? Would I have to use parameters instead like /Categories?id={id}/
How would this relationship work?
My answers are based on "pragmatic REST".
QUESTION 1: Categories
If you go with plural or singular form then I would suggest sticking with it and not jump between singular and plural... this is subjective.
If you go with singular form, then the list path action sounds applicable. If you go with plural then I think it is more subjective... IMHO list removes ambiguity and I would prefer it.
QUESTION 2: Subcategories. (Think "Seinfeld" as a subcategory of "Television".)
IMHO sub-category sounds like a separate resource. I think it should have its own path element.
Would I do /api/v1/categories/{id}/ for the Subcategory with the subcat_id? Would I have to use parameters instead like /Categories?id={id}/
I think that /api/v1/subcategories/{id}/ is more popular. But one thing that is becoming more popular is searching criteria. ID might just be one of many search criteria. If you see yourself adding search criteria then /api/v1/subcategories/?id={id} or /api/v1/subcategories/?filter={some_search_string} where you decide how that search string is parsed.
The most important thing to consider is that you are able to grow (extend) your API without changing these initial decisions you are making now. Its easy to add to an API but harder to alter existing API design once it is being used.
The URI structure is an implementation detail, it does not matter by REST as long as your service fulfills the uniform interface constraint, which is about applying the relevant standards. In your case the URI structure must fulfill the URI standard and you have to use a hypermedia format, which contains hyperlinks. So in your case /api/v1/sdfh34gsv/123regf3 would be completely okay as long as it is in a hyperlink and there is sufficient metadata available to understand what that hyperlink does. E.g. with HAL+JSON:
{
"_links": {
"/api/v1/docs/rels/category": {
"href": "/api/v1/sdfh34gsv/123regf3",
"title": "Television"
}
}
}
By processing such a response the client will recognize the "/api/v1/docs/rels/category" link relation, so it will know that it is a hyperlink to a category, which title is "Television" and the details of the category can be retrieved by following the link. If the client does not know the /api/v1/docs/rels/category link relation, then it can dereference the URI and and probably it will get some description in RDF, which it can use to display the hyperlink in a more basic form. Ofc, if developers dereference the same URI, they can get a HTML description of the link relation.
By most of the REST services this does not happen, because they use vendor specific MIME types and probably plain JSON, which violates the HATEOAS constraint, but I guess it is more practical in some cases.
async getAllCategorySubCategoryAndGroupCategoryDetail(): Promise < CategoryDetails[] > {
try {
let categoryGroupQuery = `SELECT shrt_category_groups.id as categoryGroupId,
shrt_category_groups.category_group_name as categoryGroupName,
concat('${ENV.IMG_SERVER}',shrt_category_groups.category_group_image) AS categoryGroupImage,
shrt_category_groups.is_active as isActive,
shrt_category_groups.sort_order as sortOrder
FROM shrt_category_groups where shrt_category_groups.is_active = '1' `;
let categoryGroupList = await pool.query(categoryGroupQuery);
if (categoryGroupList.length > 0) {
let categoryListQuery = `SELECT shrt_categories.id as categoryId,
shrt_categories.category_name as categoryName,
shrt_categories.category_image as categoryImage,
shrt_categories.is_active as isActive,
shrt_categories.category_group_id as categoryGroupId
FROM shrt_categories where shrt_categories.is_active = '1'`;
let categoryList = await pool.query(categoryListQuery);
let subcategoryQuery = `SELECT shrt_sub_categories.id as subCategoryId,
shrt_sub_categories.is_active as isActive,
shrt_sub_categories.subcategory_commission as commission,
shrt_sub_categories.commission_type as commissionType,
shrt_sub_categories.sub_category_name as subCategoryName,
shrt_sub_categories.category_id as categoryId
FROM shrt_sub_categories where shrt_sub_categories.is_active = '1'`;
let subCategoryList = await pool.query(subcategoryQuery);
const getCategory = (categoryGroupId: any) => {
return categoryList.filter((cat: any) => cat.categoryGroupId == categoryGroupId)
}
const getSubCategory = (categoryId: any) => {
return subCategoryList.filter((subCategory: any) => subCategory.categoryId == categoryId)
}
let mergeData = categoryGroupList.map((catG: any) => {
return { ...catG,
category: getCategory(catG.categoryGroupId).map((cat) => {
return { ...cat,
subCategory: getSubCategory(cat.categoryId)
}
})
}
})
return mergeData;
} else {
return categoryGroupList;
}
} catch (error) {
throw error;
}
}
{
"data": [
{
"categoryGroupId": 1,
"categoryGroupName": "Cloud",
"categoryGroupImage": null,
"isActive": "1",
"sortOrder": null,
"category": [
{
"categoryId": 1,
"categoryName": "Kinder & Baby",
"categoryImage": null,
"isActive": "1",
"categoryGroupId": 1,
"subCategory": [
{
"subCategoryId": 17,
"isActive": "1",
"commission": null,
"commissionType": null,
"subCategoryName": "Shirts",
"categoryId": 1
},
{
"subCategoryId": 20,
"isActive": "1",
"commission": null,
"commissionType": null,
"subCategoryName": "Jacken",
"categoryId": 1
},
{
"subCategoryId": 21,
"isActive": "1",
"commission": null,
"commissionType": null,
"subCategoryName": "Organic Collection",
"categoryId": 1
},
{
"subCategoryId": 22,
"isActive": "1",
"commission": null,
"commissionType": null,
"subCategoryName": "Baby",
"categoryId": 1
},
{
"subCategoryId": 23,
"isActive": "1",
"commission": null,
"commissionType": null,
"subCategoryName": "Hoodies & Sweatshirts",
"categoryId": 1
}
]
}
]
}
]
}