I have an array named ticketCart and it store ticket that users add, if I have an objects that looks something like this with same id on it, how can I distinguish with other objects that have a same id?
ADDEDKEY Array [
Object {
"desc": "tunjukkan tiket saat masuk",
"idTicket": "47",
"name": "vip",
"price": "70000",
"quota": "1459",
"status": "Available",
"type": "PAID",
"value": 2,
},
Object {
"desc": "tunjukkan tiket saat masuk",
"idTicket": "47",
"name": "vip",
"price": "70000",
"quota": "1459",
"status": "Available",
"type": "PAID",
"value": 2,
},
]
I tried to do something like forEach on it but it doesn't work, id (number) is still the same (In here, I'm using number as an id)
ticketCart.forEach((o, key) => {
ticketCart[key].number = key + 1;
})
Thanks
What do you mean by distinguish? What are you trying to achieve?
For example, you could identify each object by it's index in the array:
for (let i = 0; i < ticketCart.length; i++) {
ticketCart[i].number = ticketCart[i].id + "_" + i;
}
Related
I have an array with objects having "category" & "price" properties among others, in the Angular application I need to display only unique values of "category" property (Example: Economy, Premium & Deluxe) along with the lowest price in that category. I tried filtering it but was unable to achieve it. So can you please help how this can be achieved in Angular? Thank you.
In this example, I need to show:
Economy - Starts from 250USD
Premium - Starts from 400USD
Deluxe - Starts from 600USD
"hotelRooms": [
{
"price": {
"total": 250,
"currency": "USD"
},
"category": "Economy",
"subcategory": "single",
},
{
"price": {
"total": 350,
"currency": "USD"
},
"category": "Economy",
"subcategory": "double",
},
{
"price": {
"total": 450,
"currency": "USD"
},
"category": "Economy",
"subcategory": "family",
},
{
"price": {
"total": 400,
"currency": "USD"
},
"category": "Premium",
"subcategory": "single",
},
{
"price": {
"total": 500,
"currency": "USD"
},
"category": "Premium",
"subcategory": "double",
},
{
"price": {
"total": 600,
"currency": "USD"
},
"category": "Deluxe",
"subcategory": "single",
},
{
"price": {
"total": 700,
"currency": "USD"
},
"category": "Deluxe",
"subcategory": "double",
}
]
And in Angular:
<div *ngFor="let room of hotelRooms">
<span class="bold">{{ room.category }}</span> - Starts from {{ room.price.total}}{{ room.price.currency}}
</div>
From what I understand on this question, you need to group by category and next get the lowest price.amount for each category.
Concept (TL;DR)
Group By Category
1.1 Create an array for each category if the category array does not exist. Else reuse the created category array.
1.2 From each category array, find the lowest record based on price.amount.
1.3 If the result (from 1.2) return no value (undefined), first reset category array to empty array and add the current record to the category array. This ensures that each category will only have 1 record with the lowest price. Else just ignore it.
Data Transformation
2.1 Get the item from each category via iterate with key. It will return arrays.
2.2 Concat multiple arrays (from 2.1) into one array.
let groupByCategories = [];
groupByCategories = this.hotelRooms.reduce(function (previous, current) {
previous[current.category] = previous[current.category] || [];
let lowest = previous[current.category].find(
(x) =>
x.price.total < current.price.total
);
if (!lowest) {
previous[current.category] = [];
previous[current.category].push(current);
}
return previous;
}, Object.create(null));
this.hotelRooms = [].concat(
...Object.keys(groupByCategories).map((key) => {
return groupByCategories[key];
})
);
Sample Demo on StackBlitz
{
"Catalog": {
"shirts": [
{
"id": "93453951-8427394-234723908",
"name": "Demin Shirt",
"price": 100.0,
"category": "Random Category",
"available": true,
},
{
"id": "93453951-8427394-40325978",
"name": "Random Shirt",
"price": 500.0,
"category": "Random Category",
"available": true,
}
],
"Jeans": [
{
"id": "4802345-348579-5983452-23423",
"name": "Bare Denim Jeans",
"price": 2000.0,
"category": "Some Category",
"available": true,
},
{
"id": "143682137-3481293-239842",
"name": "Levis jeans",
"price": 1000.0,
"category": "Some Category",
"available": true,
}
]
}
}
How do I traverse this array of objects such that I am able to display all the different types of shirt under the category shirt and all the jeans under the heading jeans.
Something like this:
Shirts
Denim Shirt.
Random Shirt
Jeans
Bare Denim Jeans
Levis jeans
Generic Solution
This is an object, not a list, so you can't just plug it into a loop. If you want to loop through all the values and sub-values, you will have to do it recursively.
void recurseObject(dynamic value) {
if (value is List) {
// value is a list, iterate over its children
for (var child in value) {
recurseObject(object);
}
} else if (value is Map) {
// value is an object, iterate over its keys and recurse the corresponding values
for (var key in object.keys) {
print(key);
recurseObject(object[key]);
}
} else {
// value is a primitive, so just print it
print(value);
}
}
Specific to your Object
If your object has a set structure, then you can just grab all the bits you want and set up some nested loops.
final catalog = rootObj['Catalog'] as Map<String, Dynamic>;
for (var category in catalog.keys) {
final categoryList = catalog[category] as List<dynamic>;
print(category);
for (var value in categoryList) {
final name = value['name'];
print(name);
}
}
What you have there is pure JSON. You need to first convert it into a Dart object.
There are a few ways to do the conversion. I've found the easiest way is to use an online converter such as this website: https://app.quicktype.io/
After you convert your JSON to an object, you could traverse it like this:
printCatalog() {
var catalog =
Catalog.fromRawJson("Here's where you need to pass in your JSON");
print("Shirts: ");
catalog.shirts.forEach((shirt) {
print(shirt.name);
});
print("Jeans: ");
catalog.jeans.forEach((jean) {
print(jean.name);
});
}
Just use dart:convert library, and json.decode. Then access whatever you want in your json.
I fixed your JSON as it wasn't set up right, here is the complete solution.
import 'dart:convert';
void main() {
var jsonstring = '''{
"Catalog": {
"shirts": [{
"id": "93453951-8427394-234723908",
"name": "Demin Shirt",
"price": 100.0,
"category": "Random Category",
"available": "true"
},
{
"id": "93453951-8427394-40325978",
"name": "Random Shirt",
"price": 500.0,
"category": "Random Category",
"available": true
}
],
"Jeans": [{
"id": "4802345-348579-5983452-23423",
"name": "Bare Denim Jeans",
"price": 2000.0,
"category": "Some Category",
"available": true
},
{
"id": "143682137-3481293-239842",
"name": "Levis jeans",
"price": 1000.0,
"category": "Some Category",
"available": true
}
]
}
}''';
Map<String, dynamic> data = json.decode(jsonstring);
print("--COOL SHIRTS--");
for (var shirt in data["Catalog"]["shirts"]) {
print(shirt["name"]);
}
print("\n--COOL JEANS--");
for (var jeans in data["Catalog"]["Jeans"]) {
print(jeans["name"]);
}
}
Output:
--COOL SHIRTS--
Demin Shirt
Random Shirt
--COOL JEANS--
Bare Denim Jeans
Levis jeans
I know how to operate on array of objects but never had the necessity to push one array data into another. I need to push an array of objects into another array with only 2 fields of the object. Right now my object format is somewhat like this
data: [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
I want to push this into another array but I want only courseid and name in the object. I've read that we need to initialise the object in the constructor, use slice() and a few other functions and then push but I don't know how can I do it for mine since I need to push one array data into another.Kindly someone help me in this regard.
You're looking for the array map() method:
const newArray = array.map(o => {
return { name: o.name, courseid: o.courseid };
});
Try this:
let data = [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
let other = []; // your other array...
data.map(item => {
return {
courseid: item.courseid,
name: item.name
}
}).forEach(item => other.push(item));
console.log(JSON.stringify(other))
// => [{"courseid":"1","name":"Btech"},{"courseid":"2","name":"BCom"}]
You can simply do it like this.
//assign your array of object to variable
var youArray:Array<any>= [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
var resultArray:Array<any>=[] //empty array which we are going to push our selected items, always define types
youArray.forEach(i=>{
resultArray.push(
{
"name":i.name,
"courseid":i.courseid
});
});
console.log(resultArray)
if you still have doubts about this.please follow this url
Map to a returning JSON data, subscribe it to an existing array or an empty one. #typescript
let pictimeline= [];
var timeline = this.picService.fetchtimeline(this.limit)
.map((data : Response) => data.json())
.subscribe(pictimeline=> this.pictimeline = pictimeline);
console.log(this.pictimeline);
Hi I am implementing a chart in my Angularjs Application, You can see this plunker http://jsfiddle.net/fusioncharts/73xgmacm/ The thing which I want to achieve is to change the value attribute to profit. How can I do this ? I want to display profit not values.
Regards
After 2 days I finally find out the answer. The thing is You cannot change the Fusionchart attribute value but you can change the attribute of your API once you fetched. I used a loop after I fetched the API and replace the 'profit' attribute with value in this way I made the chart. Yes The thing which i had been ignoring was the use of 'variable' instead of scope. If you see this example you would understand Example Here. I am sharing my code May be it helps someone else too.
Give below is my json array which i called tps.json
[
{
"index": "1",
"variantoption": "fan-green",
"company": "sk fans",
"quantity": "650",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "2",
"variantoption": "fan-white",
"company": "al ahmed fans",
"quantity": "450",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "3",
"variantoption": "fan-purple",
"company": "asia fans",
"quantity": "350",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "4",
"variantoption": "fan-yellow",
"company": "falcon fans",
"quantity": "250",
"profit": "78296",
"loss": "8457",
"year": "2016"
}
]
and here is my controller
$http.get('js/tps.json').success(function (data) {
var chartdata = data;
var arrLength = chartdata.length;
console.log(arrLength);
for (var i = 0; i < arrLength; i++) {
if (chartdata[i]['profit'] && chartdata[i]['index']) {
chartdata[i].value = chartdata[i].profit;
delete chartdata[i].profit;
chartdata[i].label = chartdata[i].index;
delete chartdata[i].index;
console.log(chartdata);
}
}
console.log(chartdata);
FusionCharts.ready(function () {
var tps = new FusionCharts({
type: 'column2d',
renderAt: 'chart-container',
width: '500',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Monthly",
"xaxisname": "Month",
"yaxisname": "Revenue",
"numberprefix": "$",
"showvalues": "1",
"animation": "1"
},
"data" : chartdata
}
});
tps.render();
});
}
);
}
-Stay foolish stay hungry
I'm new in Node.JS and I'm able to parse the JSON data and do a console log to print out name and badges.
var details = JSON.parse(body);
console.log(details.name, details.badges.length);
But I don't know how I can get the data inside the arrays of the bagdes such as id, name, url.
I tried
console.log(details.badges.length.id);
But nothing shows up. How can I access that? Thank you.
{
"name": "Andrew Chalkley",
"badges": [
{
"id": 49,
"name": "Newbie",
"url": "http:\/\/teamtreehouse.com\/chalkers",
"icon_url": "https:\/\/achievement-images.teamtreehouse.com\/Generic_Newbie.png",
"earned_date": "2012-07-23T19:59:34.000Z",
"courses": [
]
},
{
"id": 26,
"name": "Introduction",
"url": "http:\/\/teamtreehouse.com\/library\/html\/introduction",
"icon_url": "https:\/\/achievement-images.teamtreehouse.com\/HTML_Basics.png",
"earned_date": "2012-07-23T21:57:24.000Z",
"courses": [
{
"title": "HTML",
"url": "http:\/\/teamtreehouse.com\/library\/html",
"badge_count": 1
},
{
"title": "Introduction",
"url": "http:\/\/teamtreehouse.com\/library\/html\/introduction",
"badge_count": 1
}
]
}
}
It is an array, so you need the index, for example: details.badges[0].id
This will return the first (index 0) element id.
.length only returns the length of the array, so it will not be useful to get the data in it.