AngularJs object Sorting - javascript

I have JSON like this inside the main Array Object
obj = [{{"title":"1-Introduction"},
{"title":"5-Introduction"},
{"title":"20-Introduction"},
{"title":"4-Introduction"} }]
I want to sort the above object like
obj = [{{"title":"1-Introduction"},
{"title":"4-Introduction"},
{"title":"5-Introduction"},
{"title":"20-Introduction"} }]
what I have tried so far
$scope.checkWeightage=function(){
thisObj.scheduleSubject.map(itm=>itm.sectionRange.map(subItm=>{
var min = subItm.chapterActualWeightage-(subItm.chapterActualWeightage/10);
var max = subItm.chapterActualWeightage+(subItm.chapterActualWeightage/10);
var sum = subItm.items.reduce((total,it)=>{
return total+it.actualWeightage;
},0);
subItm['weightageError'] = (sum>max || sum<min)?true:false;
subItm['ChapterActualWeightageCurrently'] = parseFloat(Math.round(sum*100)/100);
subItm.items.sort((a,b)=>a.title.split(/_(.+)/)[0]>b.title.split(/_(.+)/)[0]);
})
); console.log(thisObj.scheduleSubject[0].chapterData); //.1[0].title);
//console.log("CHECK weightage",thisObj.scheduleSubject);
}
How to track title on my main Array
alert(thisObj.scheduleSubject[0].sectionRange[0].items[0].title);
I want to sort all the items on the base of its title digits before - character example 1- , 2- ,3- ,4-, 5-, 6-, 21-,56- and so on.
Main Array Structure
[
{
"id": "25",
"section": "1",
"sectionRange": [
{
"sectionNumber": 1,
"effectAllowed": "all",
"Date": "",
"items": [
{
"subjectId": 25,
"section": 1,
"chapterId": 283,
"actualWeightage": 3.42,
"totalPaperMarks": 132,
"title": "10-Creation & Registration of Charges",
"$$hashKey": "object:146"
},
{
"subjectId": 25,
"section": 1,
"chapterId": 284,
"actualWeightage": 2.23,
"totalPaperMarks": 132,
"title": "11-Allotment of Securities & Issue of Certificates",
"$$hashKey": "object:147"
},
{
"subjectId": 25,
"section": 1,
"chapterId": 285,
"actualWeightage": 1.37,
"totalPaperMarks": 132,
"title": "12-Membership in a Company",
"$$hashKey": "object:148"
},
{
"subjectId": 25,
"section": 1,
"chapterId": 286,
"actualWeightage": 3.42,
"totalPaperMarks": 132,
"title": "13-Transfer & Transmission of Securities",
"$$hashKey": "object:149"
},
{
"subjectId": 25,
"section": 1,
"chapterId": 287,
"actualWeightage": 7.53,
"totalPaperMarks": 132,
"title": "14-Institution of Directors",
"$$hashKey": "object:150"
},
{
"subjectId": 25,
"section": 1,
"chapterId": 288,
"actualWeightage": 1.37,
"totalPaperMarks": 132,
"title": "15-Independent Directors",
"$$hashKey": "object:151"
},
{
"subjectId": 25,
"section": 1,
"chapterId": 289,
"actualWeightage": 13.35,
"totalPaperMarks": 132,
"title": "16-Board & its Powers",
"$$hashKey": "object:152"
},
{
"subjectId": 25,
"section": 1,
"chapterId": 290,
"actualWeightage": 8.22,
"totalPaperMarks": 132,
"title": "17-Appointment & Remuneration of Key Managerial Personnel",
"$$hashKey": "object:153"
},
{
"subjectId": 25,
"section": 1,
"chapterId": 291,
"actualWeightage": 6.68,
"totalPaperMarks": 132,
"title": "18-General Meetings",
"$$hashKey": "object:154"
},
{
"subjectId": 25,
"section": 1,
"chapterId": 292,
"actualWeightage": 1.37,
"totalPaperMarks": 132,
"title": "19-Loans & Investments by Companies",
"$$hashKey": "object:155"
}

You can split on that char and sort via that (assuming your main data structure is named structure:
structure.forEach(s => {
s.sectionRange.forEach(sr => {
sr.items.sort(function(a, b) {
let aParts = a.split("-"),
bParts = b.split("-");
return +aParts[0] - +bParts[0];
});
});
});

Just extract those number values and let orderBy filter of angularjs do the job for you
JS
$scope.getNumber = function(row){
var value = row.title.split("-")[0];
return parseInt(value);
};
html
<div ng-repeat="item in data | orderBy:getNumber:false">{{item.title}}</div>
also orderBy takes a second parameter (true / false) for asc / desc ordering
Demo

You can use a Array.prototype.sort with a simple sort function in which you parse the title value of each object in the array as an int and compare. Something like this:
var arr = [{
"title": "1-Introduction"
},
{
"title": "5-Introduction"
},
{
"title": "20-Introduction"
},
{
"title": "4-Introduction"
}
];
arr.sort(function(a, b) {
const aVal = parseInt(a.title.split("-")[0]);
const bVal = parseInt(b.title.split("-")[0]);
return aVal - bVal;
});
console.log(arr);

Related

setting object key dynamically in javascript

I have an object like this:
let inputData = {
"dimensions": [
{
"id": "dimension_re",
"label": "Region",
"values": ["East", "East", "West", "SouthWest", "South","NorthEast"]
},
{
"id": "dimension_cnt",
"label": "County",
"values": ["London", "Italy", "Germany", "US", "Russia","India"]
},
{
"id": "measure_sales",
"label": "Sales",
"values": [100, 156, 432, 462, 25,100]
},
{
"id": "measure_qty",
"label": "Quantity",
"values": [85, 34, 153, 434, 52, 43]
},
{
"id": "measure_profit",
"label": "Profit",
"values": [123, 45, 421, 465, 451, 56]
}
]
}
My expected output:
let expectdData = [
{
"Region": "East",
"County": "London",
"Sales": 100,
"Quantity": 85,
"Profit": 123
},
{
"Region": "East",
"County": "Italy",
"Sales": 156,
"Quantity": 34,
"Profit": 45
},
{
"Region": "West",
"County": "Germany",
"Sales": 432,
"Quantity": 153,
"Profit": 421
},
{
"Region": "SouthWest",
"County": "US",
"Sales": 462,
"Quantity": 434,
"Profit": 465
},
{
"Region": "South",
"County": "Russia",
"Sales": 25,
"Quantity": 52,
"Profit": 451
},
{
"Region": "NorthEast",
"County": "India",
"Sales": 100,
"Quantity": 43,
"Profit": 56
}
]
Here is my program to get this expected data:
let actualData = [];
inputData.dimensions.forEach((e,i) => {
let tempVal = e.label;
e.values.forEach((elem,index) => {
actualData[index] = new Object({
[tempVal] : elem
});
})
});
console.log(actualData);
But unfortunately, I only get the last item for every object. In my console it looks like this:
[
{ Profit: 123 },
{ Profit: 45 },
{ Profit: 421 },
{ Profit: 465 },
{ Profit: 451 },
{ Profit: 56 }
]
I think, in every iteration, it just overrides the "tempVal" variable. How to prevent this & how can I achieve the expected array of objects?
You are replacing the whole object on each iteration, you just need to create it if it does not exists, otherwise you can replace the key.
let actualData = [];
inputData.dimensions.forEach((e,i)=>{
let tempVal = e.label;
e.values.forEach((elem,index) => {
if (!actualData[index]) {
actualData[index] = {}
}
actualData[index][tempVal] = elem
})
});
console.log(actualData);
Using Array#reduce, iterate over dimension while updating a list of the resulting objects
In each iteration, use Array#forEach to iterate over the current values list and update the object at each index with label as key and the current value as value
const inputData = {
"dimensions": [
{
"id": "dimension_re",
"label": "Region",
"values": ["East", "East", "West", "SouthWest", "South","NorthEast"]
},
{
"id": "dimension_cnt",
"label": "County",
"values": ["London", "Italy", "Germany", "US", "Russia","India"]
},
{
"id": "measure_sales",
"label": "Sales",
"values": [100, 156, 432, 462, 25,100]
},
{
"id": "measure_qty",
"label": "Quantity",
"values": [85, 34, 153, 434, 52, 43]
},
{
"id": "measure_profit",
"label": "Profit",
"values": [123, 45, 421, 465, 451, 56]
}
]
};
const res = inputData.dimensions.reduce((acc, { label, values = [] }) => {
values.forEach((value, index) => {
acc[index] = { ...(acc[index] ?? {}), [label]: value };
});
return acc;
}, []);
console.log(res);
Since your index comes from the inner loop, you'll be replacing the values at actualData[index] each outer loop iteration, that's why you only end up with the last.
Try this reduce operation instead...
const inputData = {"dimensions":[{"id":"dimension_re","label":"Region","values":["East","East","West","SouthWest","South","NorthEast"]},{"id":"dimension_cnt","label":"County","values":["London","Italy","Germany","US","Russia","India"]},{"id":"measure_sales","label":"Sales","values":[100,156,432,462,25,100]},{"id":"measure_qty","label":"Quantity","values":[85,34,153,434,52,43]},{"id":"measure_profit","label":"Profit","values":[123,45,421,465,451,56]}]};
// Find the max number of `values`
const maxLength = Math.max(...inputData.dimensions.map(({ values }) => values.length));
const actualData = inputData.dimensions.reduce(
(arr, { label, values }) =>
arr.map((obj, i) => ({ ...obj, [label]: values[i] })),
Array.from(
{
length: maxLength,
},
() => ({}) // creates an array of empty objects
)
);
console.log(actualData);
.as-console-wrapper { max-height: 100% !important; }

How can I iterate over this object to to get a new object?

I am relatively new to Javascript, and just learned basic for loops and for in loops. How can I iterate over this object to get certain keys and values? there are a bunch of nested objects in objects, so i am kind of confused. I was thinking of using some sort of "Object...()" method, but not sure which one to use.
desired output outcome is an object with the given champion key, followed by the champion id/name = {"266": "Aatrox", "103" : "Ahri"}
example input below
"type": "champion",
"format": "standAloneComplex",
"version": "10.16.1",
"data": {
"Aatrox": {
"version": "10.16.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade",
"blurb": "Once honored defenders of Shurima against the Void, Aatrox and his brethren would eventually become an even greater threat to Runeterra, and were defeated only by cunning mortal sorcery. But after centuries of imprisonment, Aatrox was the first to find...",
"info": {
"attack": 8,
"defense": 4,
"magic": 3,
"difficulty": 4
},
"image": {
"full": "Aatrox.png",
"sprite": "champion0.png",
"group": "champion",
"x": 0,
"y": 0,
"w": 48,
"h": 48
},
"tags": [
"Fighter",
"Tank"
],
"partype": "Blood Well",
"stats": {
"hp": 580,
"hpperlevel": 90,
"mp": 0,
"mpperlevel": 0,
"movespeed": 345,
"armor": 38,
"armorperlevel": 3.25,
"spellblock": 32.1,
"spellblockperlevel": 1.25,
"attackrange": 175,
"hpregen": 3,
"hpregenperlevel": 1,
"mpregen": 0,
"mpregenperlevel": 0,
"crit": 0,
"critperlevel": 0,
"attackdamage": 60,
"attackdamageperlevel": 5,
"attackspeedperlevel": 2.5,
"attackspeed": 0.651
}
},
"Ahri": {
"version": "10.16.1",
"id": "Ahri",
"key": "103",
"name": "Ahri",
"title": "the Nine-Tailed Fox",
"blurb": "Innately connected to the latent power of Runeterra, Ahri is a vastaya who can reshape magic into orbs of raw energy. She revels in toying with her prey by manipulating their emotions before devouring their life essence. Despite her predatory nature...",
"info": {
"attack": 3,
"defense": 4,
"magic": 8,
"difficulty": 5
},
"image": {
"full": "Ahri.png",
"sprite": "champion0.png",
"group": "champion",
"x": 48,
"y": 0,
"w": 48,
"h": 48
},
"tags": [
"Mage",
"Assassin"
],
"partype": "Mana",
"stats": {
"hp": 526,
"hpperlevel": 92,
"mp": 418,
"mpperlevel": 25,
"movespeed": 330,
"armor": 20.88,
"armorperlevel": 3.5,
"spellblock": 30,
"spellblockperlevel": 0.5,
"attackrange": 550,
"hpregen": 6.5,
"hpregenperlevel": 0.6,
"mpregen": 8,
"mpregenperlevel": 0.8,
"crit": 0,
"critperlevel": 0,
"attackdamage": 53.04,
"attackdamageperlevel": 3,
"attackspeedperlevel": 2,
"attackspeed": 0.668
}
}```
const obj = {
name: 'Sam',
old: 30,
nested: {
data: 'ABC',
time: '3:15'
}
}
for(let i in obj){
console.log(i); //returns values
console.log(obj[i]); //returns keys
for(let j in obj[i]){
console.log(j); //returns values of nested 2d level
console.log(obj[i][j]); //returns keys of nested 2d level
}
}

How to get a specific object from whole object?

I am trying to get specific object from a whole object below is the example
by using localStorage.getItem('shop/elasticCache/shirt');
I get below data
{"description":"Tech Shirt","configurable_options":[{"attribute_id":80,"values":[{"value_index":"5176","label":"RUST"}],"label":"Color","attribute_code":"color"},{"attribute_id":125,"values":[{"value_index":"2898","label":"Small"},{"value_index":"2901","label":"Medium"},{"value_index":"2904","label":"Large"}],"label":"Size","attribute_code":"size"}],"tsk":1594790209,"size_options":[2898,2901,2904],"regular_price":28,"final_price":null,"price":28,"color_options":[5176],"special_from_date":null,"id":250659,"category":[{"category_id":2,"name":"Default Category","position":1},{"category_id":3,"name":"Clothing","position":14985},{"category_id":30,"name":"Bottoms","position":798},{"category_id":58,"name":"Leggings","position":1},{"category_id":1130,"name":"Char Test Category","position":30}],"sku":"S155551","product_links":[{"link_type":"related","linked_product_sku":null,"linked_product_type":null,"position":0,"sku":"P100031"},{"link_type":"related","linked_product_sku":null,"linked_product_type":null,"position":0,"sku":"P100031"}
I am trying to get
{"category_id":3,"name":"Clothing","position":14985},{"category_id":30,"name":"Bottoms","position":798},{"category_id":58,"name":"Leggings","position":1},{"category_id":1130,"name":"Char Test Category","position":30}]
Is their any way it can be done ?
const {category} = JSON.parse(localStorage.getItem('shop/elasticCache/shirt');)
or
const {category } = {
"description": "Tech Shirt",
"configurable_options": [{
"attribute_id": 80,
"values": [{
"value_index": "5176",
"label": "RUST"
}],
"label": "Color",
"attribute_code": "color"
}, {
"attribute_id": 125,
"values": [{
"value_index": "2898",
"label": "Small"
}, {
"value_index": "2901",
"label": "Medium"
}, {
"value_index": "2904",
"label": "Large"
}],
"label": "Size",
"attribute_code": "size"
}],
"tsk": 1594790209,
"size_options": [2898, 2901, 2904],
"regular_price": 28,
"final_price": null,
"price": 28,
"color_options": [5176],
"special_from_date": null,
"id": 250659,
"category": [{
"category_id": 2,
"name": "Default Category",
"position": 1
}, {
"category_id": 3,
"name": "Clothing",
"position": 14985
}, {
"category_id": 30,
"name": "Bottoms",
"position": 798
}, {
"category_id": 58,
"name": "Leggings",
"position": 1
}, {
"category_id": 1130,
"name": "Char Test Category",
"position": 30
}],
"sku": "S155551",
"product_links": [{
"link_type": "related",
"linked_product_sku": null,
"linked_product_type": null,
"position": 0,
"sku": "P100031"
}, {
"link_type": "related",
"linked_product_sku": null,
"linked_product_type": null,
"position": 0,
"sku": "P100031"
}]
}
objc={"description":"Tech Shirt","configurable_options":
[{"attribute_id":80,"values":[{"value_index":"5176","label":"RUST"}],
"label":"Color","attribute_code":"color"},
{"attribute_id":125,"values":[{"value_index":"2898","label":"Small"}
,{"value_index":"2901","label":"Medium"},
{"value_index":"2904","label":"Large"}],
"label":"Size","attribute_code":"size"}],
"tsk":1594790209,"size_options":[2898,2901,2904]
,"regular_price":28,"final_price":null,"price":28,
"color_options":[5176],"special_from_date":null,"id":250659,
"category":[{"category_id":2,"name":"Default Category","position":1},
{"category_id":3,"name":"Clothing","position":14985},
{"category_id":30,"name":"Bottoms","position":798},
{"category_id":58,"name":"Leggings","position":1},
{"category_id":1130,"name":"Char Test Category","position":30}],
"sku":"S155551","product_links":
[{"link_type":"related","linked_product_sku":null,"linked_product_type":null,"position":0,"sku":"P100031"},
{"link_type":"related","linked_product_sku":null,"linked_product_type":null,"position":0,"sku":"P100031"}]
}
res = objc["category"]
res.shift()
console.log(res)
$(document).ready(function () {
var jsonObj = {
"description": "Tech Shirt",
"configurable_options": [{
"attribute_id": 80,
"values": [{
"value_index": "5176",
"label": "RUST"
}],
"label": "Color",
"attribute_code": "color"
}, {
"attribute_id": 125,
"values": [{
"value_index": "2898",
"label": "Small"
}, {
"value_index": "2901",
"label": "Medium"
}, {
"value_index": "2904",
"label": "Large"
}],
"label": "Size",
"attribute_code": "size"
}],
"tsk": 1594790209,
"size_options": [2898, 2901, 2904],
"regular_price": 28,
"final_price": null,
"price": 28,
"color_options": [5176],
"special_from_date": null,
"id": 250659,
"category": [{
"category_id": 2,
"name": "Default Category",
"position": 1
}, {
"category_id": 3,
"name": "Clothing",
"position": 14985
}, {
"category_id": 30,
"name": "Bottoms",
"position": 798
}, {
"category_id": 58,
"name": "Leggings",
"position": 1
}, {
"category_id": 1130,
"name": "Char Test Category",
"position": 30
}],
"sku": "S155551",
"product_links": [{
"link_type": "related",
"linked_product_sku": null,
"linked_product_type": null,
"position": 0,
"sku": "P100031"
}, {
"link_type": "related",
"linked_product_sku": null,
"linked_product_type": null,
"position": 0,
"sku": "P100031"
}]
};
for(var i = 1; i < jsonObj.category.length; i++){
console.log(jsonObj.category[i]);
}
});
You can iterate through the entire object and can get the required values. The above code gives the values of category from index 1.

Access elements of array within object [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
I have scraped this object using puppeteer but it contains more information than I actually need. How do I access "height" within "components"? I have been googling for a while and have not found a solution that works.
{
"components": [{
"height": "1.8",
"period": 11,
"trueDirection": 139,
"compassDirection": "SE"
}, {
"height": "5.5",
"period": 8,
"trueDirection": 72,
"compassDirection": "ENE"
}, {
"height": "1",
"period": 13,
"trueDirection": 207,
"compassDirection": "SSW"
}],
"unit": "ft",
"title": "2-3<small class=\"unit\">ft</small>\n",
"fadedRating": 0,
"solidRating": 1,
"time": "Noon",
"date": "Thu 14/02",
"isBigWave": false
}
To extract an array containing all the height values, use map like so:
const data = {
"components": [{
"height": "1.8",
"period": 11,
"trueDirection": 139,
"compassDirection": "SE"
}, {
"height": "5.5",
"period": 8,
"trueDirection": 72,
"compassDirection": "ENE"
}, {
"height": "1",
"period": 13,
"trueDirection": 207,
"compassDirection": "SSW"
}],
"unit": "ft",
"title": "2-3<small class=\"unit\">ft</small>\n",
"fadedRating": 0,
"solidRating": 1,
"time": "Noon",
"date": "Thu 14/02",
"isBigWave": false
};
const heights = data.components.map(e => e.height);
console.log(heights);
Here I use .forEach to iterate through the components array then you can access each height easily.
const obj = {
"components": [{
"height": "1.8",
"period": 11,
"trueDirection": 139,
"compassDirection": "SE"
}, {
"height": "5.5",
"period": 8,
"trueDirection": 72,
"compassDirection": "ENE"
}, {
"height": "1",
"period": 13,
"trueDirection": 207,
"compassDirection": "SSW"
}],
"unit": "ft",
"title": "2-3<small class='\\unit\\'>ft</small>\\n",
"fadedRating": 0,
"solidRating": 1,
"time": "Noon",
"date": "Thu 14/02",
"isBigWave": false
}
obj.components.forEach(c => console.log(c.height))

Filter json object in JavaScript with a combination of Union and Intersection

const myJSON = {
"seller1": [
{
"product": "headphones",
"price": 23,
"weight": 1
},
{
"product": "earphone",
"price": 12,
"weight": 1
},
{
"product": "iPhone",
"price": 999,
"weight": 3
},
{
"product": "ipad",
"price": 399,
"weight": 4
}
],
"seller2": [
{
"product": "headphones",
"price": 25,
"weight": 1
},
{
"product": "earphone",
"price": 10,
"weight": 1
},
{
"product": "iPhone",
"price": 949,
"weight": 2
},
{
"product": "ipad",
"price": 449,
"weight": 3
}
]
}
I need to filter myJSON from a multi-select box where, if user selects product: iPhone and product: headphones, I need to display all the products that matches iPhone and headphones. In this case, myJSON will be
const myJSON = {
"seller1": [
{
"product": "headphones",
"price": 23,
"weight": 1
},
{
"product": "iPhone",
"price": 999,
"weight": 3
}
],
"seller2": [
{
"product": "headphones",
"price": 25,
"weight": 1
},
{
"product": "iPhone",
"price": 949,
"weight": 2
},
]
}
Now if the user selects different key, price: 449, myJSON should now be empty coz there is not property price: 449 in that anymore. But, if price: 23 then,
const myJSON = {
"seller1": [
{
"product": "headphones",
"price": 23,
"weight": 1
}
]
}
So for example, if user selects 3 items with same key(product), the we should show all the three items that match these 3 items from original json. Now when he selects a different key(price), then we should only filter from the previous result.
Any suggestion on how to implement this is much appreciated.

Categories