Custom sort array in Javascript [duplicate] - javascript

This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Sort an array of object by a property (with custom order, not alphabetically)
(7 answers)
Closed 4 years ago.
Let's say I have the following array:
[
{
"key":"Certified?",
"value":"Yes"
},
{
"key":"Language",
"value":"EN"
},
{
"key":"Training-Place",
"value":"City"
}
]
I want to sort it in a specific order of Language, Certified?, Training-Place, how can I achive that? Preferably I would be able to define the sorting like:
["Language", "Certified?", "Training-Place"]
Thank you very much, any help is appreciated.

You can simply use Arrays.sort() and use a order array to sort the array in the order specified by the order array.
Try the following:
var arr = [ { "key":"Certified?", "value":"Yes" }, { "key":"Language", "value":"EN" }, { "key":"Training-Place", "value":"City" }, { "key":"Training-Place", "value":"aaa" }, { "key":"Language", "value":"bbb" }];
var order = ["Language", "Certified?", "Training-Place"];
arr.sort((a,b)=> order.indexOf(a.key) - order.indexOf(b.key));
console.log(arr);

Create an array which will contain the order. Now loop over this array and from the main array filter out the object which matches with the name
let arrayToSort = [{
"key": "Certified?",
"value": "Yes"
},
{
"key": "Language",
"value": "EN"
},
{
"key": "Training-Place",
"value": "City"
}
]
let sortOrder = ["Language", "Certified?", "Training-Place"]
let customSortArray = [];
sortOrder.forEach(function(item) {
customSortArray.push(
arrayToSort.filter(function(items) {
return item === items.key
})[0])
})
console.log(customSortArray)

Related

Find index of an object in an arrray of objects [duplicate]

This question already has answers here:
How can I get the index of an object by its property in JavaScript?
(22 answers)
Closed 1 year ago.
I have an array that looks like this:
const arr = [
{ "-MrUU6N2pi7aCwJoqCzP": { "name": "test", "brand": "test", "id": 1 } },
{ "-MrUUB4PcPD5G45NGb-y": { "name": "test2", "brand": "test2", "id": 2 } }
]
How do I find the index of the object with the key "-MrUUB4PcPD5G45NGb-y" for example?
You can use findIndex() and look at the Object.keys() for each object in the array to see if the key you want is in that keys array
const arr = [
{"-MrUU6N2pi7aCwJoqCzP":{"name":"test","brand":"test","id":1}},
{"-MrUUB4PcPD5G45NGb-y":{"name":"test2","brand":"test2","id":2}}
],
keyWanted = "-MrUUB4PcPD5G45NGb-y",
idx = arr.findIndex(e => Object.keys(e).includes(keyWanted))
console.log('Index =', idx)

How to populate the string template variables in an array of objects in javascript? [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 4 years ago.
I've created an array of object and in some of these objects I need to refer to the properties of that object inside of it like this:
let fields = [
{
"ATTRIBUTE_NAME": "PERSON_NAME",
"FIELD_NAME": "name"
"ATTRIBUTE_ID": 1,
"RULES": [
{
"MSG":`${this.ATTRIBUTE_NAME} is not valid`,
"NAME": "VALID_VALUES",
}
]
},
{
"ATTRIBUTE_NAME": "PERSON_JOB",
"FIELD_NAME": "job"
"ATTRIBUTE_ID": 2,
"RULES": [
{
"MSG":`${this.ATTRIBUTE_NAME} is not valid`,
"NAME": "VALID_VALUES",
}
]
}
]
But this keyword returning undefined! I want the "MSG" property to pick up the attribute name and populate it for me. Does anybody know how to capture it inside the template string?
The easiest way would be to use a getter for your RULES property.
A simple demonstration:
var obj = {
id: 1,
get info() {
return `The id is ${this.id}.`;
}
}
console.log(obj.info);
Applied to your code:
let fields = [{
"ATTRIBUTE_NAME": "PERSON_NAME",
"FIELD_NAME": "name",
"ATTRIBUTE_ID": 1,
get RULES() {
return [{
"MSG": `${this.ATTRIBUTE_NAME} is not valid`,
"NAME": "VALID_VALUES",
}]
}
}];
console.log(fields[0].RULES[0].MSG);
You can't use a self-reference like that, because the fields array and its sub-elements have not yet been declared. What you can do, instead, is:
Declare the fields array and its sub-elements first.
Then, iterate over every element and add the object you want in the RULES array.
Example:
/* Declare the array and its sub-elements. */
let fields = [{
"ATTRIBUTE_NAME": "PERSON_NAME",
"FIELD_NAME": "name",
"ATTRIBUTE_ID": 1,
"RULES": []
},
{
"ATTRIBUTE_NAME": "PERSON_JOB",
"FIELD_NAME": "job",
"ATTRIBUTE_ID": 2,
"RULES": []
}
];
/* Iterate over every element. */
fields.forEach(element => {
element.RULES.push({
"MSG": element.ATTRIBUTE_NAME + " is not valid",
"NAME": "VALID_VALUES"
});
});
/* Log the result. */
console.log(fields);

Finding JSON path inside object [duplicate]

This question already has answers here:
Convert string in dot notation to get the object reference [duplicate]
(6 answers)
Closed 8 years ago.
How to check in an JSON object, the input path is present or not?
var obj = {
"schemaOne": {
"name": "abc",
"Path": "i.abc",
"count": 5347,
"subFolders": [
]
},
"schemaTwo": {
"name": "cde",
"Path": "i.cde",
"count": 0,
"subFolders": [
{
"name": "efg",
"Path": "",
"count": 0,
"subFolders": [
]
},
{
"name": "hij",
"Path": "i.hij",
"count": 1,
"subFolders": [
]
}
]
}
}
var inputpath = "obj.count";
After doing several research I came across below code. Here in this code, o.Path is known to the user. But I want to modify the code so tat dynamically check obj.count is present in JSON object or not?
function upd(o, path, count) {
if (o.Path == path) {
o.count = count;
} else {
var arr;
if (Array.isArray(o)) arr = o;
else if (o.subFolders) arr = o.subFolders;
else return;
for(var j=0; j < arr.length; j++) {
upd(arr[j], path, count);
}
}
}
Your question isn't very clear, neither the use case. As someone told u, obj is a JavaScript object, not a JSON.
If I understood correctly, you want to check if a path, espressed as string (such as "obj.count") exists in that object.
A very fast but not safe solution (eval is evil and should be avoided almost in every case) could be:
if(eval(inputpath)){
//... do something
}
In alternative, I suggest you to write a function that gets an object and a string (path) as parameter, parses the string path and check if the object contains such path.
Start from here: Accessing nested JavaScript objects with string key

How to sort JSON by a single integer field? [duplicate]

This question already has answers here:
Sort array of objects by single key with date value
(19 answers)
Closed 8 years ago.
I have the following JSON:
{
title: 'title',
...,
order: 0
}, {
...,
order: 9
}, {
...,
order: 2
}
... the JSON includes many fields, how can I sort them based on the order field?
I was looking for something build into nodejs but I couldn't find anything that might be useful for that case.
At first, your need valid JSON, like that:
var unsorted = {
"items": [
{
"title": "Book",
"order": 0
},
{
"title": "Movie",
"order": 9
},
{
"title": "Cheese",
"order": 2
}
]
};
Afterwards you can easily sort the items and store them in a list.
var sorted = unsorted.items.sort(function(a, b) {return a.order - b.order});
Demo: http://jsfiddle.net/6eQbp/2/
You can use the Array.sort() method to do the sorting.
Ref: http://www.javascriptkit.com/javatutors/arraysort.shtml
A quick way would be to use a library like underscore.js - it's got a lot of functions that help you do exactly this kind of manipulation with JSON objects.
I've not tested this, but something along these lines:
_.sortBy(yourJSONdata, function(obj){ return +obj.order });

How do I access the responses/response ID's in this JSON string with javascript? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 10 years ago.
Hi guys I am using parseJSON to parse this JSON string:
json = [
{
"Answers": [
{
"Responses": [
],
"AnswerID": 1,
"AnswerText": "Green"
},
{
"Responses": [
{
"ResponseID": 1,
"RespondingUser": null,
"ResponseDate": "\/Date(1351694241577)\/"
},
{
"ResponseID": 2,
"RespondingUser": null,
"ResponseDate": "\/Date(1351694245093)\/"
}
],
"AnswerID": 2,
"AnswerText": "Blue"
}
],
"QuestionID": 1,
"QuestionText": "Favourite colour?",
"ClosingDate": "\/Date(1351953058527)\/",
"AskingUser": null
}
]
var result = jQuery.parseJSON(json);
but how do I get the responses/response ID's out of 'result' now? Any help would be greatly appreciated!
[ ] = array
{ } = object
You have an array, lose the wrapping square brackets.
alert(json.Answers[0].AnswerText) = "Green"
You should be able to use the for-in loop:
for (i in result[0].Answers)
{
// do something with result[0].Answers[i].Responses
}
Is this what you're looking for?
for (var a in result[0].Answers) {
result[0].Answers[a].AnswerID // Do something with it.
}

Categories

Resources