Sorting json objects by specific value - javascript

I am sending data that I have already sorted by number of counts, from my controller in Laravel to my script file. Json data that I am sending looks like this:
{"5":{"title":"Coop post title","summary":"dbsbsb","count":5},
"7":{"title":"Example article","summary":"fdsbdfsbsffd","count":5},
"6":{"title":"Coop's post","summary":"sdbadbb","count":3},
"0":{"title":"sdvsdv","summary":"dsvsdv","count":2},
"4":{"title":"sdvsdv","summary":"dsvsdv","count":1}}
But when I parse json data like this in my script file data gets random again:
var cleanData = $.parseJSON(data);
console.log(cleanData);
And then I get in console data that looks like this:
Object {0: Object, 4: Object, 5: Object, 6: Object, 7: Object}
0:Object
count:2
summary:"dsvsdv"
title:"sdvsdv"
__proto__:Object
4:Object
count:1
summary: "dsvsdv"
title: "sdvsdv"
__proto__:Object
5:Object
count:5
summary: "dbsbsb"
title: "Coop post title"
__proto__: Object
6:Object
count:3
summary: "sdbadbb"
title: "Coop's post"
__proto__: Object
7:Object
count:5
summary: "fdsbdfsbsffd"
title: "Example article"
__proto__: Object

You can sort using lodash#sortBy:
_.sortBy(collection, [iteratees=[_.identity]])
Creates an array of elements, sorted in ascending order by the results of running each element in a collection (Array|Object) thru each iteratee. This method performs a stable sort, that is, it preserves the original sort order of equal elements. The iteratees are invoked with one argument: (value).
var cleanData = {"5":{"title":"Coop post title","summary":"dbsbsb","count":5},"7":{"title":"Example article","summary":"fdsbdfsbsffd","count":5},"6":{"title":"Coop's post","summary":"sdbadbb","count":3}, "0":{"title":"sdvsdv","summary":"dsvsdv","count":2}, "4":{"title":"sdvsdv","summary":"dsvsdv","count":1}};
cleanData = _.sortBy(cleanData, ['count']);
console.log(cleanData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

Related

Within a nested array, can I create an array of the keys at each index?

Goal: For each key, assign every value to an array.
Use case: I have to be able to search using all possible values simultaneously. As seen at the bottom, a possible key:value search would be:
"LocationNumber": [1,2,3,4]}
The problem: Object SettingOptions is a nested array.
This is how I log each key within a given index:
//Defines array 'keysArray'
const keysArray = [];
pm.test("array of SettingsOptions[0] keys", () => {
arrayOfObject = responseDataLocal.Products[0].ConfigurationModel.SettingOptions[0]; //object 'SettingOptions[0]' calls 1st settingoption
//For each property in array, add the property to 'keysArray'
for (var property in arrayOfObject) {
keysArray.push(property)
}
console.log(keysArray)
});
Response:
(11) ["LocationNumber", …]
0: "LocationNumber"
1: "StoneCount"
2. ....
....
9: "Shape"
10: ...
To create an array of values from a given property:
pm.test("array of SettingsOptions objects", () => {
arrayOfObject = responseDataLocal.Products[0].ConfigurationModel.SettingOptions;
let arrayLocationNumber = arrayOfObject.map(a => a.LocationNumber);
// console.log(Object.values(arrayLocationNumber));
});
Response:
[1, 2, 3, 4]
What I'm looking for:
There is a lot of variation in the data I'm pulling from. So I need to be able to automagically pull values to be able to reference them in subsequent requests. An acceptable response could look something like:
0.{"LocationNumber": [1,2,3,4]}
1....
2.......
3.{"Shape": ["Center","Halo","Accent 1","Accent 2"]}

Converting JSON to array key - value in javascript

I've been developing a web application where I'm receiving data in this format, from a node server:
"{""elements":[{"10sr2b2":{"total":0,"bad":22,"clients":["fc8e7f","fc8e7e"],"zone":"101900"}}]}"
The poblem is this data is an array key-value called "elements" where "10sr2b2" is the key of the first element of the array.
So when I call $.parseJSON() method, this return an object like this:
elements: Array[1]
0: Object
10sr2b2: Object
zone: "101900"
clients: Array[2]
0: "fc8e7f"
1: "fc8e7e"
length: 2
__proto__: Array[0]
bad: 22
total: 0
Where "10sr2b2" it's supposed to be the key and it's an object and I need to get this value somehow.
Can you help me?
You could use Object.keys to get the object keys.
var keys = Object.keys(data.elements[0]);
Can you change the format from the node server? It needs to send something more like:
"{""elements":[{"key": "10sr2b2" "value": {"total":0,"bad":22,"clients":"fc8e7f","fc8e7e"],"zone":"101900"}}]}"
If you know you'll always only have one key for each item, you can use a for..in loop that immediately breaks, for example
var i, key, obj = $.parseJSON(/*...*/);
for (i = 0; i < obj.elements.length; ++i) { // loop over elements
for (key in obj.elements[i]) break; // get key
// now can access
obj.elements[i][key]; // Object
}

how to create JavaScript object using a for loop?

i have an object sample data:
[Object, Object, Object]
0: Object
test_id: "1"
area: "high"
1: Object
test_id: "1"
area: "saw"
2: Object
test_id: "2"
area: "look"
i am trying to create a new object by grouping by test_id.
var obj = new Object();
$.each(data, function(k, v){
obj[v.test_id] += {area: v.area};
});
this doesn't seem to work, it returns only one object line...
i am trying to get something like:
1: {
{area: "high"}
{area: "saw"}
}
2: {
{area: "look""
}
any ideas? thanks
After your edit I notice something, you're trying to create a javascript object with a property with no name, this is not the format. In JSON (javascript object notation) each property must have a value, what you are trying to store better fits an array.
Instead, push it into an array
$.each(data, function(k, v){
obj[v.test_id].area.push(v.area);
});
just remember to create obj[v.test_id] first and to set its area property to [].
This results in:
1: {
area: ["high","saw"]
}
3: {
area: ["look"]
}
Also, if you're willing to consider using underscore it has very powerful (yet basic) collection methods, you might want to have a look at http://underscorejs.org/#groupBy

Javascript object is in array but can't access it

I have a for loop which iterates through currentObject in response.
This code:
console.log(response[currentObject]);
Clearly shows that response[currentObject] has among other properties, "start".
However, this code tells me the variable is undefined:
console.log(response[currentObject].start);
Why is this? Note that "start" is a date variable.
Here is the whole function:
function(response) {
for (var currentObject in response) {
//Parsing the data before its used
//"17\/10\/2012 20:55:00"
var phpStartDate = response[currentObject].start;
console.log(response[currentObject]);
var phpStopDate = response[currentObject].stop;
var datePartsStart = phpStartDate.match(/(\d+)/g);
var datePartsStop = phpStopDate.match(/(\d+)/g);
var parsedDateStart = new Date(datePartsStart[2], datePartsStart[1], datePartsStart[0], datePartsStart[3], datePartsStart[4], datePartsStart[5]);
var parsedDateStop = new Date(datePartsStop[2], datePartsStop[1], datePartsStop[0], datePartsStop[3], datePartsStop[4], datePartsStop[5]);
response[currentObject].start = parsedDateStart;
response[currentObject].stop = parsedDateStop;
//debugger;
};
return response;
}
Forgot to add, I'm using jQuery 1.8.2, which I believe handles dates differently than 1.7 (but I can't use 1.7 because I had a whole bunch of other problems with it!)
Here is the output of console.log(response):Object
data: Array[3]
0: Object
hourly: "4.00"
id: "40"
staff: "James Hadley"
start: "2012-09-25 00:00:00"
stop: "2012-09-27 00:00:00"
__proto__: Object
1: Object
hourly: "25.00"
id: "39"
staff: "James Hadley"
start: "2012-10-17 21:12:00"
stop: "2012-10-26 02:30:00"
__proto__: Object
2: Object
length: 3
__proto__: Array[0]
total: 3
__proto__: Object
I guess it's a timing issue, because the console.log object is live. Try
console.log(JSON.stringify(response[currentObject]));
I bet it does NOT include start even thought without stringify it does. Your response is asynchronous and you access start too early (your code doesn't show that part).
Now with your comment it's obvious. It's an array and you are missing and index, e.g. 0.
console.log(response[currentObject][0].start);
use
currentObject.start = parsedDateStart
instead of
response[currentObject].start = parsedDateStart

difference between 2 objects/arrays

i have 2 objects, which are associated arrays from PHP in JSON. They have an structure like that´:
[object]
["green"]
['value1']=integer
['value1']=array...
["blue"]
['value1']=integer
['value1']=array...
[...]
The 1st Version of this object is loaded from webserver periodically using JSON.
By receiving this new JSON string from webserver, the current object moved to the variable "oldObj" while the new data stored into the variable "newObj".
It could be possible, that the new object will have less elements than the old object, like this:
[newObj]
["green"]
['value1']=integer
['value1']=array...
As you can see: "blue" is missing.
Now i need this elements which are part of the old Object / that means: which are missing at the new object (at this example: element "blue")
I tried the following, but without any success:
[...]
var newObj=data;
$.each (oldObj,function(i,n)
{if (newObj.i.length<1) {alert('missing: '+i);}
}
);//end foreach
Error message: "newObj.i is undefined"
According to your description, I think newObj or oldObj can be wrote as:
var newObj = {
"green": [
integer,
[array]
],
"blue": [
integer,
[array]
]
};
Is it right?
You could use :
for(p in Obj){
if(Obj.hasOwnProperty(p)){
// do something with p
}
}
to loop through the Obj's properties.

Categories

Resources