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
Related
How can I concatenate this json to obtain it:
complements = ["XYZ 3, CDE TR, AAA 5", "", "NDP 3, DDD FR"] ?
Each address can contain a set of complements which must be concatenated and separated by a comma.
P.s: I'm using javascript.
P.s2: Complements can be null like in the second group in JSON.
[
{
"postalcode": "1234",
"street": "ABC",
"number": "1",
"complement": [
{
"type": "B",
"name": "XYZ",
"description": "3"
},
{
"type": "C",
"name": "CDE",
"description": "TR"
},
{
"type": "D",
"name": "AAA",
"description": "5"
}
]
},
{
"postalcode": "444",
"street": "No complements",
"number": "5"
},
{
"postalcode": "2222",
"street": "BBB",
"number": "2",
"complement": [
{
"type": "E",
"name": "NDP",
"description": "3"
},
{
"type": "F",
"name": "DDD",
"description": "FR"
}
]
}
];
My code I'm getting this.complementsList.forEach is not a function.
getComplement(addressesResponse){
this.complementsList = JSON.parse(addressesResponse);
this.complementsList.forEach((item) => {
Object.defineProperty(item, 'complements', {
get: function() {
return this.complement.map((c) => `${c.name} ${c.description}`).join(', '); }
})
});
Source: https://salesforce.stackexchange.com/questions/367713/how-to-render-a-json-in-the-same-line-lwc
how i solved it :
arr.map((x)=>x.complement != null? (x.complement.map((y)=>y.name+' '+y.description)+"") :'');
Having a javascript object, you can go through the keys of the object and combine some of them into strings
It will look something like this:
const jsonObject = [{...}, {...}, ...]
const complements = [];
jsonObject.forEach((item) => {
let complement = item['complement'].reduce((result, currObj)
=> result += (currObj.name+' '+currObj.description), "");
complements.push(complement);
});
This is just an example. There are many ways to do it.
var brands = [];
brands = [null, {
"id": "1",
"image": "/images/brands/surf_excel.png",
"name": "Surf Excel",
"productCount": "6"
}, {
"id": "2",
"image": "/images/brands/rin.png",
"name": "Rin",
"productCount": "5"
}, {
"id": "3",
"image": "/images/brands/ariel.png",
"name": "Ariel",
"productCount": "4"
}];
Now i want to get the name where id = 3. I tried
var data = _.filter(brands, { 'id': 3 });
console.log(data.name);
But its giving error can't read property of undefined. Assuing there will be only one record for id =3, Can anyne help me on this. How to get name from given id in the above structure.
If there is any better way to get the same result that is also appreciated.
As you have specified lodash and using it's _.filter() method. You can use pass predicate which can a function which will be invoke per iteration. As note it will return you an array.
var data = _.filter(brands, function(brand){
return brand != null && brand.id == 3;
});
console.log(data[0].name);
if you want only one element the use _.find()
var data = _.find(brands, function(brand){
return brand != null && brand.id == 3;
});
console.log(data.name);
Use native JavaScript Array#find method.
var brands = [];
brands = [null, {
"id": "1",
"image": "/images/brands/surf_excel.png",
"name": "Surf Excel",
"productCount": "6"
}, {
"id": "2",
"image": "/images/brands/rin.png",
"name": "Rin",
"productCount": "5"
}, {
"id": "3",
"image": "/images/brands/ariel.png",
"name": "Ariel",
"productCount": "4"
}];
var data = brands.find(function(v) {
return v && v.id == "3";
});
console.log(data.name);
Check polyfill option for find method for older browser.
If you want to filter out the array then use Array#filter method.
var brands = [];
brands = [null, {
"id": "1",
"image": "/images/brands/surf_excel.png",
"name": "Surf Excel",
"productCount": "6"
}, {
"id": "2",
"image": "/images/brands/rin.png",
"name": "Rin",
"productCount": "5"
}, {
"id": "3",
"image": "/images/brands/ariel.png",
"name": "Ariel",
"productCount": "4"
}];
var data = brands.filter(function(v) {
return v && v.id == "3";
});
console.log(data[0].name);
UPDATE :
You are provided an object as the second argument as per documentation which uses _.matches for property value comparison. In your array id property holds a string value but you were provided as a number in the filter just change it to string will make it work or use callback function as in #Satpal answer.
var brands = [];
brands = [null, {
"id": "1",
"image": "/images/brands/surf_excel.png",
"name": "Surf Excel",
"productCount": "6"
}, {
"id": "2",
"image": "/images/brands/rin.png",
"name": "Rin",
"productCount": "5"
}, {
"id": "3",
"image": "/images/brands/ariel.png",
"name": "Ariel",
"productCount": "4"
}];
var data = _.filter(brands, {
'id': "3"
});
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.js"></script>
Aside from using filter() instead of find(), you're actually pretty close. The reason you're not seeing any results is because the object predicates that you can pass to find()/filter() perform strict equality comparisons. Meaning, 3 === '3' will evaluate to false.
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>');
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.
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);
}
}