JSON Array - Extract Data With Javascript - javascript

I have a really simple Json array and I need to get back
the number of items within the array.
the list of entries in order of the id.
The array is as follows:
{"error":false,"error_msg":"","body":
{"records":[{"name":"Application","id":1},
{"name":"Fees Paid","id":2},
{"name":"Evidence Verification","id":3},
{"name":"Details QA","id":4},
{"name":"Grade Approval","id":5},
{"name":"Welcome Pack","id":6}]
},
"validation_errors":[]}

Assuming you have JSON.parsed your string into a variable called jsonobj, the following statements get the data you want:
var len = jsonobj.body.records.length;
jsonobj.body.records.sort(function(a,b) {return a.id-b.id;});
// now iterate through jsonobj.body.records and they will be in ascending ID order

Say you have your Object held in variable jObj, clone the Array/Objects so you preserve the originals, sort it as desired then return an Array which just holds the name properties.
jObj['body']['records']
.map(function (e) {return {'id': e['id'], 'name': e['name']};}) // clone
.sort(function (a, b) {return +a['id'] - +b['id'];}) // sort asc
.map(function (e) {return e['name'];}); // get names
/* [
"Application", "Fees Paid", "Evidence Verification",
"Details QA", "Grade Approval", "Welcome Pack"
] */

Related

How to sort the nested object data in react-native

{
"lion":{
"age_in_years":"10",
"name":"king",
"country":"africa"
},
"elephant":{
"age_in_years":"15",
"name":"hero",
"country":"usa"
},
"racoon":{
"age_in_years":"5",
"name":"thanos",
"country":"syria"
},
}
This is the data I'm getting through a web socket in react-native. I want to sort it in ascending order based on the "age_in_years". So the oldest animal's data should be shown at top and the youngest data at the last.
You sould better work with an array insted of object as below, first map it into array and parse the age_in_years and sort it.
const obj2Array = Object.entries(<YourObject>).map(([key, value]) => ({...value, _id: key, age_in_years: parseInt(value.age_in_years)}));
const sorted = obj2Array.sort((a, b) => a.age_in_years - b.age_in_years);
Then you can use .reduce if you want the object back, nevertheless you can use the sorted array to render it.
Sort by age in years oldest first
// use slice() to copy the array
var byAge = array.slice(0);
byAge.sort(function(a,b) {
return a.age_in_years - b.age_in_years ;
});
Store the values in array and make a sort function.
const numbers = [info.lion.age_in_years, info.elephant.age_in_years, info.racoon.age_in_years];
const ascNumbers = numbers.sort((a,b) => a-b);
If you need descending make it like this:
const descNumbers = numbers.sort((a,b) => b-a);

When specifying a custom key in object, it turns it into an number

When I implement a string based number in a object as the key, when the object is rendered, its returned as a number instead of a string. This is throwing me off because my original array is reordered and then i want to generate an object based of a number which is an ID within the array row but the issue is, by default, javascript is reordering my object keys by numerical ordered list, instead of the order i tell it to be in.
var array = ['1','2','3'].reverse();
var obj = {};
$.each(array, (idx, item) => {
obj[item.toString()] = item;
});
console.log(array, obj);
return is
(3) ["3", "2", "1"] {1: "1", 2: "2", 3: "3"}
instead of
(3) ["3", "2", "1"] {3: "3", 2: "2", 1: "1"}
however, this works total fine with non numerical type characters, example below:
var array = ['hi','tom','how'].reverse();
var obj = {};
$.each(array, (idx, item) => {
obj[item.toString()] = item;
});
console.log(array, obj);
return as expected
(3) ["how", "tom", "hi"] {how: "how", tom: "tom", hi: "hi"}
by default, javascript is reordering my object keys by numerical ordered list, instead of the order i tell it to be in
Object properties are not ordered. There are various ways to get a list of or iterate over properties, but for most of them the order is implementation dependent. However, most current browsers will first iterate over numeric properties in ascending order and then over non-numeric properties in insertion order.
If you want guaranteed order then you should use a Map as explained in the other answer, because maps maintain insertion order, or keep using your array to define iteration order.
You can use Map to store properties in a specific order
var array = ['1','2','3'].reverse();
var obj = new Map;
array.forEach((item, idx) => {
obj.set(item.toString(), item);
});
console.log([...obj.entries()]);
array.forEach((item, idx) => {
console.log(obj.get(item))
});
console.log(obj);

Summation of JSON values in an Array

I have a set of JSON data stored in an array. The JSON looks like this:
{
"id": "1",
"key": "2"
}
and I'm trying to sum all of the "key" values inside the array of JSON strings with a for/in loop.
var total = 0;
for (var object in array) {
total += object.value;
}
The expected output is 3. However, this arrangement seems incorrect. I'm working in Node.js. Can anyone point me in the right direction?
If we have an array looking like this:
var array = [{id: "one", key: 2}, {id: "two", key: 8}]
You can simply get the total like that:
var total = array.reduce((x,y) => x + y.key, 0)
However, if you have a JSON string, where the values are also strings (like [{"id":"one","key":"2"},{"id":"two","key":"8"}]'), then you need to parse the JSON first and parse the values as numbers:
JSON.parse(array).reduce((x,y) => x + Number.parseFloat(y.key), 0)
What you have is not an array of objects, but one object with several properties.
You can use Object.keys() to get the properties as an array, then map to retrieve the values for each of those properties, and finally reduce on that array to calculate the sum:
const obj = {
"id": "1",
"key": "2"
}
const total = Object.keys(obj) // Get keys
.map( key => +obj[key] ) // Get values as numbers
.reduce ( (a,b) => a+b ); // sum up
console.log(total);

Issue with creating an array from an object in javascript?

I have an object that I need to transform into an array. Here is the code I have already:
for (var key in categoryData[p]) { // categorydata is an object, the "p" is because this is taking place in a loop (array of objects)
if (categoryData[p].hasOwnProperty(key)) {
var objToArray = $.map(categoryData[p], function(value, key) {
return [value];
});
}
}
Right now, this is returning:
0 : value
1 : value
2 : value
I want it to return:
Key : Value
Key : Value
Key : Value
But I haven't found a way to do this with my data. Any direction would be greatly appreciated!
Edit: Adding more information:
I want to sort from the highest to lowest value. For clarification, I want the data to look like this:
(key) (object)
"ABC" : 8
"DEF" : 7
"GHI" : 5
I am putting it into an array to begin with because I can't sort the values when they're in an object (as far as I know).
My data is fairly complex, in a CSV file, but the idea of it is:
ABC, DEF, GHI
8 , 7 , 5
Associative arrays aren't a thing in javascript. You can either have arrays denoted by [] with 0 based numeric indices, or objects denoted by {} that can store key-value pairs. The latter construct can be used as replacement to associative arrays (ie add arbitrary keys and values to it), but they cannot be treated like arrays.
What you want in this case is what you already have - a key/value store, except it's called an object.
edit
If you just want to sort the data regardless of datatypes
You can split your object into multiple objects with a single key-value pair, then create an array from these objects and sort them any way you like using Array.sort(). Here's a quick example of splitting your provided data into objects:
var originalData = {
"ABC" : 8,
"DEF" : 7,
"GHI" : 5,
},
sortableArray = [];
for (key in originalData) {
sortableArray.push({
"key" : key,
"value" : originalData[key]
});
}
This creates a new object and appends it to our sortable [] array. To sort it according to its original value, you need to supply a comparator function that accesses the value property of the objects.
sortableArray.sort(function(a,b) {
return a.value - b.value;
});
This should return an array of objects ordered by the value property of each object in ascending order. Simply switch a and b around to get a descending order sort.
Hope this helps!
The best approach to sort your data is to map your object into an array to look like this:
[
{
"key": someKey
"value": someValue
},
{
"key": someOtherKey
"value": someOtherValue
},
//...
]
using this code:
var objToArray = $.map(categoryData[p], function(value, key) {
return {"key": key, "value": value};
});
And then sort it using this code:
objToArray.sort(function(a, b) {
// if the values are numbers (otherwise you have to change this to addapt to your dataType)
return b.value - a.value; // to sort from highest to lowest or a.value - b.value to sort from lowest to highest
});
And then you can use it like:
objToArray[0].key; // to get the key of the first item
objToArray[3].value; // to get the value of the 4-th item
// ...
You can loop through them as well (for(var i = 0; i < objToArray.length; i++)...).
In ES6, Object.entries(a).sort((a, b) => a[1] < b[1] )
This will give you something like this
[
["ABC", 8]
["DEF", 7]
["GHI", 5]
]
the .entries step gives you the list of pairs and the .sort step sorts them by their second value

Sort by values of properties on Object in JavaScript?

I have an object like this:
I would like to do two things.
Sort the properties based on their values
I would to know the order (or index) for any given property. For example, after ordering, I would like to know that the index of 00D is the 5th.
How can I achieve this in JavaScript?
While you can not sort properties of an object, you could use an array of keys of the object, sort them and take the wanted element, you want.
var keys = Object.keys(object), // get all keys
indices = Object.create(null); // hash table for indices
// sort by value of the object
keys.sort(function (a, b) { return object[a] - object[b]; });
// create hash table with indices
keys.forEach(function (k, i) { indices[k] = i; });
// access the 5th key
console.log(keys[5]);
// get index of 00G
console.log(indices['00G']);

Categories