Sort json preserving index - javascript

I'm trying to sort the json below, but until now couldn't find the way. I get this json by jQuery ajax with datatype json. How can I apply sort to this keeping the index? Every time i try to sort javascript throws an error telling undefined is not a function. I already know that json or objects don't have sort.
So how can I achieve this? I really need to keep this index.
{
"header": {
"user": "1059",
"authenticated": true,
"isGuest": false,
"time": 1416362117
},
"batches": {
"3503": { // Preserve this index
"user": "1059",
"auction": "1826",
"number": "1",
"published": "1",
"type": "1",
"status": "1",
"date_start": "1415379600",
"date_end": "1417021200", // Sort by this value
},
"3583": {
"user": "1059",
"auction": "1886",
"auto_value": "0.00",
"number": "1",
"published": "1",
"type": "1",
"status": "1",
"date_start": "1415376000",
"date_end": "1417017600",
},
}
}

As I wrote and cited in comments - properties do not have an order. Make an array of single-property objects, which you can sort. Something like this:
var data = {
"header": {
"user": "1059",
"authenticated": true,
"isGuest": false,
"time": 1416362117
},
"batches": [ // this is an array of objects, not a single object
{"3503": { // Preserve this index
"user": "1059",
"auction": "1826",
"number": "1",
"published": "1",
"type": "1",
"status": "1",
"date_start": "1415379600",
"date_end": "1417021200", // Sort by this value
}},
{"3583": {
"user": "1059",
"auction": "1886",
"auto_value": "0.00",
"number": "1",
"published": "1",
"type": "1",
"status": "1",
"date_start": "1415376000",
"date_end": "1417017600",
}}
] // end of array
}
data.batches.sort(function(a, b) {
return a[Object.keys(a)[0]].date_end - b[Object.keys(b)[0]].date_end;
});
console.log(data.batches);
And you can keep those numbers inside of the object containing user, auction and so on for easier access.

Related

Postman - Looping through an array of nested objects to make a variable

I am trying to set a variable from following phone number with value: “+33652556777” (index 4 in JSON attached below) which is the last object in contacts (index 4).
To do so is pretty simple:
let jsonData = pm.response.json();
console.log (jsonData.contacts[4].phone_numbers[0].value)
const PhoneNumber = jsonData.contacts[4].phone_numbers[0].value
pm.environment.set("Jacky", PhoneNumber);
Since I have to use different query parameters to filter by eg. created_at=asc, desc, the property of the phone_numbers order might change index number and I won’t be able to fetch desire phone number "+33652556777” instead it will set a different phone number which I cannot allow.
I know there is way to fetch our number and make it variable for next requests, which is iterating over properties or keys in the object “ for….in or for…of ” but for some reason I cannot achieve it.
What I could achieve is to get through first object “contacts” but impossible to get to its nested array “phone_numbers”. Here is how I did it:
let jsonData = pm.response.json();
let contact;
for (let filter of jsonData.contacts){
if (filter.last_name == "Rowland"){
contact = filter;
}}
console.log (contact);
Could you please help?
Here goes the JSON body response:
{
"contacts": [
{
"id": 11121211,
"direct_link": "https://example.example",
"first_name": "test1",
"last_name": "test",
"company_name": "test",
"information": null,
"is_shared": true,
"created_at": 1582798926,
"updated_at": 1582798926,
"emails": [],
"phone_numbers": [
{
"id": 60065270,
"label": "Work",
"value": "+33134567666"
}
]
},
{
"id": 22222222,
"direct_link": "https://example.example",
"first_name": null,
"last_name": null,
"company_name": null,
"information": null,
"is_shared": true,
"created_at": 1583686067,
"updated_at": 1583686067,
"emails": [],
"phone_numbers": [
{
"id": 22266444,
"label": "Work",
"value": "+33134567899"
}
]
},
{
"id": 33333564,
"direct_link": "https://example.example",
"first_name": "Jessica",
"last_name": "Biel",
"company_name": "N-Sync",
"information": null,
"is_shared": true,
"created_at": 1583686086,
"updated_at": 1583686086,
"emails": [],
"phone_numbers": []
},
{
"id": 45678901,
"direct_link": "https://example.example",
"first_name": null,
"last_name": null,
"company_name": null,
"information": null,
"is_shared": true,
"created_at": 1583686105,
"updated_at": 1583686105,
"emails": [],
"phone_numbers": [
{
"id": 22266444,
"label": "Work",
"value": "+33134567333"
}
]
},
{
"id": 56789123,
"direct_link": "https://example.example",
"first_name": "Jacky",
"last_name": "Rowland",
"company_name": "Test Company1",
"information": "",
"is_shared": true,
"created_at": 1583745888,
"updated_at": 1608556499,
"emails": [
{
"id": 76594398,
"label": "Work",
"value": "mandatory_field#example.com"
}
],
"phone_numbers": [
{
"id": 60650277,
"label": "Mobile",
"value": "+33652556777"
}
]
}
],
"meta": {
"count": 6,
"total": 241,
"current_page": 1,
"per_page": 5,
"next_page_link": "https://example.example",
"previous_page_link": null
}
}
You could use something basic like this:
_.each(pm.response.json().contacts, (contact) => {
if(contact.last_name === "Rowland") {
pm.environment.set(`${contact.first_name}_${contact.last_name}_number`, contact.phone_numbers[0].value)
}
})
There are probably better and more performant ways to do this but if you just want to set a variable for that contact, no matter where they are in the response - This would work :D
you can use forEach or _.each as danny mentioned to get all numbers else use:
console.info(jsonData.contacts.find((a)=>a.first_name==="Jacky").phone_numbers[0].value)
use array.find to find the contact with first_name jacky adn then get phone_number[0].value from it.
if you want all numbers from that array then use:
console.info(jsonData.contacts.find((a)=>a.first_name==="Jacky").phone_numbers.map((a)=>a.value))
here we map the result to get only the numbers from phone_number array.
is it what you looking for !?

Reverse an array of object?

How can i reverse this array using react native ? i tried myarray.reverse(); but I get below error message.
TypeError: undefined is not an object (evaluating 'myarray.reverse')
const myarray =
Array [
Object {
"key": "-LrcB3Xcb4QuMtd20TSn",
"value": Object {
"question": "26",
"timestamp": 1571558541642,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
Object {
"key": "-LrcB3pf0DQuCr_vfP_2",
"value": Object {
"question": "27",
"timestamp": 1571558542861,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
]
try to remove Array and Object from the JSON. Works perfect for me.
const myarray = [{
"key": "-LrcB3Xcb4QuMtd20TSn",
"value": {
"question": "26",
"timestamp": 1571558541642,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
{
"key": "-LrcB3pf0DQuCr_vfP_2",
"value": {
"question": "27",
"timestamp": 1571558542861,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
]
myarray.reverse()
Is the pasted code what you are actually getting back from the API?
The formatting/syntax is not correct. As others have stated you shouldn't have the 'Array' and 'Object' words inline like that. I think you're copying code from a terminal/console that added those words in.
If the response actually looks like this you won't have any problem using myaray.reverse()
const myarray = [{
"key": "-LrcB3Xcb4QuMtd20TSn",
"value": {
"question": "26",
"timestamp": 1571558541642,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
{
"key": "-LrcB3pf0DQuCr_vfP_2",
"value": {
"question": "27",
"timestamp": 1571558542861,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
]

Merging two json array object based on union and intersection

I am trying to merge two json array with objects as element. You may refer to this plunkr file for both json. I have succesfully retrieve the expected final outcome array id, but I do not know how to form back the expected json as below. I am using underscore js for this purpose.
Note: If object exist in newJson and not in currentJson, after merge, it will be inactive state by default.
I am not sure whether I am using the correct approach. This is what I have try:
var newJsonID = _.pluck(newJson, 'id');
var currentJsonID = _.pluck(currentJson, 'id');
var union = _.union(newJsonID, currentJsonID);
var intersection = _.intersection(currentJsonID, newJsonID);
var final = _.difference(union, _.difference( currentJsonID, intersection);
Expected Final Outcome:
[
{
"id": "12",
"property1Name": "1"
"status": "inactive"
},
{
"id": "11",
"property1Name": "1"
"status": "inactive"
},
{
"id": "10",
"property1Name": "1"
"status": "inactive"
},
{
"id": "9",
"property1Name": "1"
"status": "active"
}
]
A solution in plain Javascript with two loops and a hash table for lookup.
function update(newArray, currentArray) {
var hash = Object.create(null);
currentArray.forEach(function (a) {
hash[a.id] = a.status;
});
newArray.forEach(function (a) {
a.status = hash[a.id] || 'inactive';
});
}
var newJson = [{ "id": "12", "property1Name": "1" }, { "id": "11", "property1Name": "1" }, { "id": "10", "property1Name": "1" }, { "id": "9", "property1Name": "1" }],
currentJson = [{ "id": "10", "property1Name": "1", "status": "inactive" }, { "id": "9", "property1Name": "1", "status": "active" }, { "id": "8", "property1Name": "1", "status": "active" }, { "id": "7", "property1Name": "1", "status": "inactive" }];
update(newJson, currentJson);
document.write('<pre>' + JSON.stringify(newJson, 0, 4) + '</pre>');

Sort array by timestamp in jquery

In AJAX response I am getting JSON array with multiple nodes. How can I sort every node by its time stamp .
Code I tried:
$$.ajax({
type:'POST',
url: "http://www.xyz.co/get_all_news.php",
dataType: "JSON",
data:{'email': window.localStorage["email"], 'business_id': localStorage.getItem("business_id")},
success: function (jsondata1){
data= JSON.parse(jsondata1);
jsondata1.sort(function(x, y){
return x.created_at - y.created_at;
})
console.log(jsondata1); //Error - Uncaught TypeError: jsondata1.sort is not a function
}
});
Also value of jsondata1 is
var jsondata1 = [
{"id":"1","body":"Bsjd djjdjd jdjdkd djjdjd jdjd","votes":"4","update_type":"7","created_at":"2015-11-21 02:03:41","name":"Nehil"},
{"id":"2","body":"#TestingBestNominations","votes":"1","update_type":"7","created_at":"2015-11-21 02:03:44","name":"Nehil"},
{"id":"1","name":"#milestone1","date":"0000-00-00","location":"Mumbai","story_body":"Hdjjdjdbj djfjjd djkdjd","short_link":"A0Ijv","created_at":"2015-11-19 05:09:41","path":"\/SupportData\/ImpalzB2B\/uploads\/90294930451447934978817.jpg","update_type":"3"},
{"id":"1","name":"Product 1","description":"Dbbxbxjjd fjkd","short_link":"CmR0X","created_at":"2015-11-19 05:28:34","path":"\/SupportData\/ImpalzB2B\/uploads\/90294930451447936111369.jpg","update_type":"4"}
]
Sorting it by (created_at) Error I am getting is
"Uncaught TypeError: jsondata1.sort is not a function".
You can treat date strings (in this case as ISO format) as string and sort it with String.prototype.localeCompare.
var jsondata1 = [
{ "id": "1", "body": "Bsjd djjdjd jdjdkd djjdjd jdjd", "votes": "4", "update_type": "7", "created_at": "2015-11-21 02:03:41", "name": "Nehil" },
{ "id": "2", "body": "#TestingBestNominations", "votes": "1", "update_type": "7", "created_at": "2015-11-21 02:03:44", "name": "Nehil" },
{ "id": "1", "name": "#milestone1", "date": "0000-00-00", "location": "Mumbai", "story_body": "Hdjjdjdbj djfjjd djkdjd", "short_link": "A0Ijv", "created_at": "2015-11-19 05:09:41", "path": "\/SupportData\/ImpalzB2B\/uploads\/90294930451447934978817.jpg", "update_type": "3" },
{ "id": "1", "name": "Product 1", "description": "Dbbxbxjjd fjkd", "short_link": "CmR0X", "created_at": "2015-11-19 05:28:34", "path": "\/SupportData\/ImpalzB2B\/uploads\/90294930451447936111369.jpg", "update_type": "4" }
];
jsondata1.sort(function (a, b) { return a.created_at.localeCompare(b.created_at); });
document.write('<pre>' + JSON.stringify(jsondata1, 0, 4) + '</pre>');
For different date type I suggest to have a look here: Sort Javascript Object Array By Date

accessing a specific set of values from within my json response?

I am trying to use for..in loop to access the description key/value within 'Event' but at the moment am not fully sure how to achieve this. First of all I used the for..in and logged this out, this returns all the top level entries in the response, how do I now drill down and pick out Event.description? I first of all thought it was data[prop].Event.description but thats not the case. Should I be using a normal for loop and then the for..in inside of this?
Here is my current code:
$(document).ready(function() {
var data = {
"status": "ok",
"code": "200",
"message": "event details",
"data": [{
"Event": {
"id": "1",
"name": "Sample Event Number 1",
"description": "Sample Event Number 4 Description ....",
"event_date": "2012-05-31 00:00:00",
"Band": [{
"id": "1",
"name": "Support #1",
"BandsEvent": {
"id": "7",
"band_id": "2",
"event_id": "8",
"created": "2012-05-23 15:53:56",
"modified": "2012-05-23 15:53:56"
}},
{
"id": "2",
"name": "Support #2",
"BandsEvent": {
"id": "8",
"band_id": "1",
"event_id": "8",
"created": "2012-05-23 15:53:57",
"modified": "2012-05-23 15:53:57"
}}]
}},
{
"Event": {
"id": "2",
"name": "Sample Event Number 2",
"description": "Sample Event Number 4 Description ....",
"event_date": "2012-05-31 00:00:00",
"Band": [{
"id": "2",
"name": "Another Crazy Band",
"BandsEvent": {
"id": "3",
"band_id": "2",
"event_id": "8",
"created": "2012-05-23 15:53:56",
"modified": "2012-05-23 15:53:56"
}},
{
"id": "4",
"name": "The Band",
"BandsEvent": {
"id": "8",
"band_id": "1",
"event_id": "8",
"created": "2012-05-23 15:53:57",
"modified": "2012-05-23 15:53:57"
}}]
}}]
}
var prop;
for (prop in data) {
console.log( data[prop] );
// data.Event.description
}
});​
This should do what you want:
for (var i = 0; i < data.data.length; i++) {
console.log(data.data[i].Event.description);
}
I should add that the reason that your code doesn't work is that the "prop" variable would first be "status", then "code", then "message" and THEN "data". Status/code/message has no "Event" property, so therefore your code would return undefined if you'd try to access data[prop].Event. Here we pick them out specifically. And since that data.data is an array, there's no reason to use a for .. in loop, but rather just a regular for loop.
Likewise, if you would want to print out the descriptions AND the bands, you could do the following:
for (var i = 0; i < data.data.length; i++) {
console.log(data.data[i].Event.description + " has the following bands:");
for (var j = 0; j < data.data[i].Event.Band.length; j++) {
console.log(data.data[i].Event.Band[j].name);
}
}

Categories