How to sort an object by keys in JavaScript - javascript

I have the following object:
Object { WK23: 12.52573059875292, WK22: 122.2625975869411, WK21:
78.48714311048059, WK20: 87.14214810403018, WK26: 78.52625051674245, WK25: 77.64480983891451, WK24: 67.42158281711342, WK2:
78.420343898902, WK3: 77.91344340707354, WK4: 77.29048185059888 }
Is it possible to sort it by keys, from WK1 to WK100 ?
How to do this in JavaScript ?
Thanks in advance,

Try this , you can change order and assign to different object
var unordered={ WK23: 12.52573059875292, WK22: 122.2625975869411, WK21: 78.48714311048059, WK20: 87.14214810403018, WK26: 78.52625051674245, WK25: 77.64480983891451, WK24: 67.42158281711342, WK2: 78.420343898902, WK3: 77.91344340707354, WK4: 77.29048185059888 }
console.log(JSON.stringify(unordered));
const ordered = {};
Object.keys(unordered).sort(function(a,b){
var a=a.split("WK")[1];
var b=b.split("WK")[1];
return a-b
}).forEach(function(key) {
ordered[key] = unordered[key];
});
console.log(JSON.stringify(ordered));

No, you can't. Object keys are not ordered. If you want to sort entries in an Object, you will have to convert it into an Array.
var obj = {"WK23": 12.52573059875292, "WK22": 122.2625975869411};
var result = Object.keys(obj).map(function(key) {
return [key, obj[key]];
});
// the result Array can then be sorted...
// result = [["WK23": 12.52573059875292], ["WK22": 122.2625975869411]]
var sorted = result.sort(function(a,b){
var num_a = parseInt(a[0].replace("WK", ""));
var num_b = parseInt(b[0].replace("WK", ""));
return num_a > num_b;
});
// sorted = [["WK22": 122.2625975869411], ["WK23": 12.52573059875292]]

here you go
const sample = { WK23: 12.52573059875292, WK22: 122.2625975869411, WK21:
78.48714311048059, WK20: 87.14214810403018, WK26: 78.52625051674245, WK25: 77.64480983891451, WK24: 67.42158281711342, WK2:
78.420343898902, WK3: 77.91344340707354, WK4: 77.29048185059888 };
const sorted = Object.keys(sample).sort().map(key => sample[key]);

Related

dynamic Object name in JSON.parse

I want use dynamic {i} in loop for access obj array after parsing like modele_{i}.view_[i] for access values
please help me to solve my problem
how can replace this line
var Ob = obj.permissions[i-1].module_1.view_1;
With
var Ob = obj.permissions[i-1].module_{i}.view_{i};
const data = '{"permissions": [{"module_1": {"view_1":"false","edit_1":"false","delete_1":"false","add_1":"false","search_1":"false"}},{"module_2": {"view_2":"false","edit_2":"false","delete_2":"false","add_2":"false","search_2":"false"}},{"module_3": {"view_3":"false","edit_3":"false","delete_3":"false","add_3":"false","search_3":"false"}},{"module_4": {"view_4":"false","edit_4":"false","delete_4":"false","add_4":"false","search_4":"false"}},{"module_5": {"view_5":"false","edit_5":"false","delete_5":"false","add_5":"false","search_5":"false"}},{"module_6": {"view_6":"false","edit_6":"false","delete_6":"false","add_6":"false","search_6":"false"}},{"module_7": {"view_7":"false","edit_7":"false","delete_7":"false","add_7":"false","search_7":"false"}},{"module_8": {"view_8":"false","edit_8":"false","delete_8":"false","add_8":"false","search_8":"false"}},{"module_9": {"view_9":"false","edit_9":"false","delete_9":"false","add_9":"false","search_9":"false"}},{"module_10": {"view_10":"false","edit_10":"false","delete_10":"false","add_10":"false","search_10":"false"}},{"module_11": {"view_11":"false","edit_11":"false","delete_11":"false","add_11":"false","search_11":"false"}},{"module_12": {"view_12":"false","edit_12":"false","delete_12":"false","add_12":"false","search_12":"false"}},{"module_13": {"view_13":"false","edit_13":"false","delete_13":"false","add_13":"false","search_13":"false"}},{"module_14": {"view_14":"false","edit_14":"false","delete_14":"false","add_14":"false","search_14":"false"}},{"module_15": {"view_15":"false","edit_15":"false","delete_15":"false","add_15":"false","search_15":"false"}},{"module_16": {"view_16":"false","edit_16":"false","delete_16":"false","add_16":"false","search_16":"false"}},{"module_17": {"view_17":"false","edit_17":"false","delete_17":"false","add_17":"false","search_17":"false"}},{"module_18": {"view_18":"false","edit_18":"false","delete_18":"false","add_18":"false","search_18":"false"}},{"module_19": {"view_19":"false","edit_19":"false","delete_19":"false","add_19":"false","search_19":"false"}},{"module_20": {"view_20":"false","edit_20":"false","delete_20":"false","add_20":"false","search_20":"false"}},{"module_21": {"view_21":"false","edit_21":"false","delete_21":"false","add_21":"false","search_21":"false"}},{"module_22": {"view_22":"false","edit_22":"false","delete_22":"false","add_22":"false","search_22":"false"}},{"module_23": {"view_23":"false","edit_23":"false","delete_23":"false","add_23":"false","search_23":"false"}},{"module_24": {"view_24":"false","edit_24":"false","delete_24":"false","add_24":"false","search_24":"false"}},{"module_25": {"view_25":"false","edit_25":"false","delete_25":"false","add_25":"false","search_25":"false"}},{"module_26": {"view_26":"false","edit_26":"false","delete_26":"false","add_26":"false","search_26":"false"}},{"module_27": {"view_27":"false","edit_27":"false","delete_27":"false","add_27":"false","search_27":"false"}},{"module_28": {"view_28":"false","edit_28":"false","delete_28":"false","add_28":"false","search_28":"false"}},{"module_29": {"view_29":"false","edit_29":"false","delete_29":"false","add_29":"false","search_29":"false"}},{"module_30": {"view_30":"false","edit_30":"false","delete_30":"false","add_30":"false","search_30":"false"}},{"module_31": {"view_31":"false","edit_31":"false","delete_31":"false","add_31":"false","search_31":"false"}},{"module_32": {"view_32":"false","edit_32":"false","delete_32":"false","add_32":"false","search_32":"false"}},{"module_33": {"view_33":"false","edit_33":"false","delete_33":"false","add_33":"false","search_33":"false"}},{"module_34": {"view_34":"false","edit_34":"false","delete_34":"false","add_34":"false","search_34":"false"}},{"module_35": {"view_35":"false","edit_35":"false","delete_35":"false","add_35":"false","search_35":"false"}},{"module_36": {"view_36":"false","edit_36":"false","delete_36":"false","add_36":"false","search_36":"false"}},{"module_37": {"view_37":"false","edit_37":"false","delete_37":"false","add_37":"false","search_37":"false"}},{"module_38": {"view_38":"false","edit_38":"false","delete_38":"false","add_38":"false","search_38":"false"}},{"module_39": {"view_39":"false","edit_39":"false","delete_39":"false","add_39":"false","search_39":"false"}},{"module_40": {"view_40":"false","edit_40":"false","delete_40":"false","add_40":"false","search_40":"false"}},{"module_41": {"view_41":"false","edit_41":"false","delete_41":"false","add_41":"false","search_41":"false"}},{"module_42": {"view_42":"false","edit_42":"false","delete_42":"false","add_42":"false","search_42":"false"}},{"module_43": {"view_43":"false","edit_43":"false","delete_43":"false","add_43":"false","search_43":"false"}},{"module_44": {"view_44":"false","edit_44":"false","delete_44":"false","add_44":"false","search_44":"false"}},{"module_45": {"view_45":"false","edit_45":"false","delete_45":"false","add_45":"false","search_45":"false"}},{"module_46": {"view_46":"false","edit_46":"false","delete_46":"false","add_46":"false","search_46":"false"}},{"module_47": {"view_47":"false","edit_47":"false","delete_47":"false","add_47":"false","search_47":"false"}},{"module_48": {"view_48":"false","edit_48":"false","delete_48":"false","add_48":"false","search_48":"false"}},{"module_49": {"view_49":"false","edit_49":"false","delete_49":"false","add_49":"false","search_49":"false"}},{"module_50": {"view_50":"false","edit_50":"false","delete_50":"false","add_50":"false","search_50":"false"}},{"module_51": {"view_51":"false","edit_51":"false","delete_51":"false","add_51":"false","search_51":"false"}},{"module_52": {"view_52":"false","edit_52":"false","delete_52":"false","add_52":"false","search_52":"false"}},{"module_53": {"view_53":"false","edit_53":"false","delete_53":"false","add_53":"false","search_53":"false"}},{"module_54": {"view_54":"false","edit_54":"false","delete_54":"false","add_54":"false","search_54":"false"}}],"count":"54"}';
const obj = JSON.parse(data);
let Size = obj.count;
for (let i=1; i <= Size ; i++) {
var Ob = obj.permissions[i-1].module_1.view_1;
console.log(Ob);
}
Since you only have one object that matches you don't need a loop. Just find the first object that matches.
const data = '{"permissions": [{"module_1": {"view_1":"false","edit_1":"false","delete_1":"false","add_1":"false","search_1":"false"}},{"module_2": {"view_2":"false","edit_2":"false","delete_2":"false","add_2":"false","search_2":"false"}},{"module_3": {"view_3":"false","edit_3":"false","delete_3":"false","add_3":"false","search_3":"false"}},{"module_4": {"view_4":"false","edit_4":"false","delete_4":"false","add_4":"false","search_4":"false"}},{"module_5": {"view_5":"false","edit_5":"false","delete_5":"false","add_5":"false","search_5":"false"}},{"module_6": {"view_6":"false","edit_6":"false","delete_6":"false","add_6":"false","search_6":"false"}},{"module_7": {"view_7":"false","edit_7":"false","delete_7":"false","add_7":"false","search_7":"false"}},{"module_8": {"view_8":"false","edit_8":"false","delete_8":"false","add_8":"false","search_8":"false"}},{"module_9": {"view_9":"false","edit_9":"false","delete_9":"false","add_9":"false","search_9":"false"}},{"module_10": {"view_10":"false","edit_10":"false","delete_10":"false","add_10":"false","search_10":"false"}},{"module_11": {"view_11":"false","edit_11":"false","delete_11":"false","add_11":"false","search_11":"false"}},{"module_12": {"view_12":"false","edit_12":"false","delete_12":"false","add_12":"false","search_12":"false"}},{"module_13": {"view_13":"false","edit_13":"false","delete_13":"false","add_13":"false","search_13":"false"}},{"module_14": {"view_14":"false","edit_14":"false","delete_14":"false","add_14":"false","search_14":"false"}},{"module_15": {"view_15":"false","edit_15":"false","delete_15":"false","add_15":"false","search_15":"false"}},{"module_16": {"view_16":"false","edit_16":"false","delete_16":"false","add_16":"false","search_16":"false"}},{"module_17": {"view_17":"false","edit_17":"false","delete_17":"false","add_17":"false","search_17":"false"}},{"module_18": {"view_18":"false","edit_18":"false","delete_18":"false","add_18":"false","search_18":"false"}},{"module_19": {"view_19":"false","edit_19":"false","delete_19":"false","add_19":"false","search_19":"false"}},{"module_20": {"view_20":"false","edit_20":"false","delete_20":"false","add_20":"false","search_20":"false"}},{"module_21": {"view_21":"false","edit_21":"false","delete_21":"false","add_21":"false","search_21":"false"}},{"module_22": {"view_22":"false","edit_22":"false","delete_22":"false","add_22":"false","search_22":"false"}},{"module_23": {"view_23":"false","edit_23":"false","delete_23":"false","add_23":"false","search_23":"false"}},{"module_24": {"view_24":"false","edit_24":"false","delete_24":"false","add_24":"false","search_24":"false"}},{"module_25": {"view_25":"false","edit_25":"false","delete_25":"false","add_25":"false","search_25":"false"}},{"module_26": {"view_26":"false","edit_26":"false","delete_26":"false","add_26":"false","search_26":"false"}},{"module_27": {"view_27":"false","edit_27":"false","delete_27":"false","add_27":"false","search_27":"false"}},{"module_28": {"view_28":"false","edit_28":"false","delete_28":"false","add_28":"false","search_28":"false"}},{"module_29": {"view_29":"false","edit_29":"false","delete_29":"false","add_29":"false","search_29":"false"}},{"module_30": {"view_30":"false","edit_30":"false","delete_30":"false","add_30":"false","search_30":"false"}},{"module_31": {"view_31":"false","edit_31":"false","delete_31":"false","add_31":"false","search_31":"false"}},{"module_32": {"view_32":"false","edit_32":"false","delete_32":"false","add_32":"false","search_32":"false"}},{"module_33": {"view_33":"false","edit_33":"false","delete_33":"false","add_33":"false","search_33":"false"}},{"module_34": {"view_34":"false","edit_34":"false","delete_34":"false","add_34":"false","search_34":"false"}},{"module_35": {"view_35":"false","edit_35":"false","delete_35":"false","add_35":"false","search_35":"false"}},{"module_36": {"view_36":"false","edit_36":"false","delete_36":"false","add_36":"false","search_36":"false"}},{"module_37": {"view_37":"false","edit_37":"false","delete_37":"false","add_37":"false","search_37":"false"}},{"module_38": {"view_38":"false","edit_38":"false","delete_38":"false","add_38":"false","search_38":"false"}},{"module_39": {"view_39":"false","edit_39":"false","delete_39":"false","add_39":"false","search_39":"false"}},{"module_40": {"view_40":"false","edit_40":"false","delete_40":"false","add_40":"false","search_40":"false"}},{"module_41": {"view_41":"false","edit_41":"false","delete_41":"false","add_41":"false","search_41":"false"}},{"module_42": {"view_42":"false","edit_42":"false","delete_42":"false","add_42":"false","search_42":"false"}},{"module_43": {"view_43":"false","edit_43":"false","delete_43":"false","add_43":"false","search_43":"false"}},{"module_44": {"view_44":"false","edit_44":"false","delete_44":"false","add_44":"false","search_44":"false"}},{"module_45": {"view_45":"false","edit_45":"false","delete_45":"false","add_45":"false","search_45":"false"}},{"module_46": {"view_46":"false","edit_46":"false","delete_46":"false","add_46":"false","search_46":"false"}},{"module_47": {"view_47":"false","edit_47":"false","delete_47":"false","add_47":"false","search_47":"false"}},{"module_48": {"view_48":"false","edit_48":"false","delete_48":"false","add_48":"false","search_48":"false"}},{"module_49": {"view_49":"false","edit_49":"false","delete_49":"false","add_49":"false","search_49":"false"}},{"module_50": {"view_50":"false","edit_50":"false","delete_50":"false","add_50":"false","search_50":"false"}},{"module_51": {"view_51":"false","edit_51":"false","delete_51":"false","add_51":"false","search_51":"false"}},{"module_52": {"view_52":"false","edit_52":"false","delete_52":"false","add_52":"false","search_52":"false"}},{"module_53": {"view_53":"false","edit_53":"false","delete_53":"false","add_53":"false","search_53":"false"}},{"module_54": {"view_54":"false","edit_54":"false","delete_54":"false","add_54":"false","search_54":"false"}}],"count":"54"}';
const obj = JSON.parse(data);
const number = 1;
const ob = obj.permissions.find(obj => {
return obj[`module_${number}`][`view_${number}`];
});
console.log(ob);

Merge and create an unique case sensitive array in javascript

It's a complicated scenario but will try to explain as much as possible. I have one object or arrays and one array. Now i have to compare selectedmodel values with mappedmodels, if the value(Case insensitive) matches with that object then fetch all the values of it and push it into selected model and combine both. Hope the example will clear what i am trying to achive.
var mappedModels = { 'CC605': ['cc605', 'CC605', 'cC605'], 'TC75X': ['TC75X'] };
var selectedModels = ['CC605', 'tc76'];
var desiredOutput = ["CC605", "tc76", "cc605", "cC605"];
I already wrote a solution to achieve it but i need a better code in terms of performance. Here is the solution:
function combineModelCases(selectedModels) {
const modelCases = [];
selectedModels.forEach(elm => {
const existingModels = mappedModels[elm.toUpperCase()];
if (existingModels) {
for (const key of existingModels) {
if (elm.toUpperCase() !== key) {
modelCases.push(key);
}
}
}
});
return selectedModels.concat(modelCases);
}
Here is Fiddle
I am using typescript and underscore js for your references. Any help would be very helpful.
You could use flatMap to get a flattened array of values for each key in selectedModels. Then, create a Set to get a unique collection models. Use Array.from() to convert the set to an array.
const mappedModels = { 'CC605': ['cc605', 'CC605', 'cC605'], 'TC75X': ['TC75X'] },
selectedModels = ['CC605', 'tc76'];
const models = selectedModels.flatMap(m => mappedModels[m] || []),
unique = Array.from(new Set([...selectedModels, ...models]));
console.log(unique)
you can do the following, :
var mappedModels = { 'CC605': ['cc605', 'CC605', 'cC605'], 'TC75X': ['TC75X'] };
var selectedModels = ['CC605', 'tc76'];
var desiredOutput;
function combineModelCases(selectedValue){
if(mappedModels.hasOwnProperty(selectedValue)){
desiredOutput = [... new Set([...mappedModels[selectedValue], ...selectedModels])]
return desiredOutput;
}
}
console.log(combineModelCases('CC605'));
here is the working demo : https://jsfiddle.net/wzo4d6uy/2/:

Organize Array Items

I have the following JavaScript array:
var allItems = ['BBL_NO1', 'BBL_NO2', 'BBL_N03', 'BBL_NO4', 'AAL_NO1', 'AAL_NO2', 'MML_NO1', 'MML_NO2'];
Now I want to sort the array in this format, to put the values in a dropdown:
var sorted = { 'BBL': ['BBL_NO1', 'BBL_NO2', 'BBL_N03', 'BBL_NO4'],
'AAL': ['AAL_NO1', 'AAL_NO2'],
'MML': ['MML_NO1', 'MML_NO2']};
Does anyone know how I can do that?
You can do it using Array.prototype.reduce() function.
Example:
var allItems = ['BBL_NO1', 'BBL_NO2', 'BBL_N03', 'BBL_NO4', 'AAL_NO1', 'AAL_NO2', 'MML_NO1', 'MML_NO2'];
var sorted = allItems.reduce(function (acc, item) {
var mainPart = item.split('_')[0];
if (!acc.hasOwnProperty(mainPart)) {
acc[mainPart] = [];
}
acc[mainPart].push(item);
return acc;
}, {});
console.log(sorted);

Insert an item to array object using underscorejs

I want to insert an id in to an existing array of objects using underscorejs.
input array
var arr = [{name:"iPhone"}, {name:"Samsung"}];
expected output array
var arr = [{name:"iPhone", owner_id: "555"}, {name:"Samsung", owner_id: "555"}];
Tried following, its working but looking for a better way
devices = []
arr.forEach(function(data) {
var device = {};
device.owner_id = "555";
device.name= data.name;
devices.push(device )
})
zip them first and then using map
var arr = [{name:"iPhone"}, {name:"Samsung"}];;
var ageArr = [{owner_id: "555"},{owner_id: "555"}];
var newArr = _.zip(arr, ageArr).map(function(v) {
return _.extend(v[0], v[1]);
});
console.log(newArr);
<script src="http://underscorejs.org/underscore-min.js"></script>
No need to use underscore. Here is an easy way using the .map method. Each object returned inside the callback will be inserted into the devices array.
var devices = arr.map(function(data) {
var device = {};
device.owner_id = "555";
device.name= data.name;
return device;
})
If you console.log devices it will print (depending on data of course):
[{name:"iPhone", owner_id: "555"}, {name:"Samsung", owner_id: "555"}];

Filter properties from an array based on another array

I have an array of objects like this:
var bridges = {"countyCd:15
createdDate:"0001-01-01T00:00:00"
createdUserId:0
createdUserIdZ:null
createdUserName:null
description:"SR 1#.-CENTRAL RR COMP OF IND"
districtId:null
encryptedId1:null
encryptedId2:null
isDirty:false
modelState:null
nbiNumber:10
routeNbr:"1"
routeTypeCd:"SR"
transactionType:null
updatedDate:"0001-01-01T00:00:00"
updatedUserId:0
updatedUserIdZ:null
updatedUserName:null", [...]....}
I have another array like this
[countyCd, nbiNumber]
How can create another array keeping just two properties so it becomes like
bridges = {"countyCd:15
nbiNumber:10"
, [...]....}
Basically, I am looking for a way to create a function that takes a data array and a filter array as parameters and filters the data array based on the filter array.
Any pointers to this will be much appreciated.
One solution would be to map over each record and reduce your filter array into an object containing the target proprties:
var bridges = [{
countyCd:15,
createdDate:"0001-01-01T00:00:00",
createdUserId:0,
createdUserIdZ:null,
createdUserName:null,
description:"SR 1#.-CENTRAL RR COMP OF IND",
districtId:null,
encryptedId1:null,
encryptedId2:null,
isDirty:false,
modelState:null,
nbiNumber:10,
routeNbr:"1",
routeTypeCd:"SR",
transactionType:null,
updatedDate:"0001-01-01T00:00:00",
updatedUserId:0,
updatedUserIdZ:null,
updatedUserName:null
}, {
countyCd:23,
createdDate:"0001-01-01T00:00:00",
createdUserId:0,
createdUserIdZ:null,
createdUserName:null,
description:"SR 1#.-CENTRAL RR COMP OF IND",
districtId:null,
encryptedId1:null,
encryptedId2:null,
isDirty:false,
modelState:null,
nbiNumber:10,
routeNbr:"1",
routeTypeCd:"SR",
transactionType:null,
updatedDate:"0001-01-01T00:00:00",
updatedUserId:0,
updatedUserIdZ:null,
updatedUserName:null
}];
var filters = ['countyCd', 'nbiNumber'];
var transformedRecords = bridges.map(bridge => filters.reduce((p, c) => {
p[c] = bridge[c];
return p;
}, {}));
console.log(transformedRecords);
Say you have an array of bridges, call it bA:
var bA = []; //bridges array
var nbiA = []; // nbia array with countyCd
var newA = []; // new array
bA.forEach(function(element, index, array){
var newEntry = {
'countyCd':element.countyCd,
'nbiNumber':nbiA.find(function(nbi){
return nbi[countyCd] == element.countyCd;
}).nbiNumber
};
newA.push(newEntry);
});
//do whatever you want with the newA array

Categories