Get data from JSON object using value within - javascript

My JSON is as follows:
{
"sales": [{
"manager": "alberic",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "USA",
"percent-seller": "30",
"antiquity": "June 2017",
"date": "6"
}, {
"manager": "support",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "UK",
"percent-seller": "20",
"antiquity": "June 2017",
"date": "2"
}, {
...
}]
}
I want to retrieve the objects from sales where manager = "support" and date = "2". How do I go about this in jQuery?
Thanks!

Simply you can use filter() method and use your condition inside filter method function will return element if your condition become true otherwise it ignore element.
data= {"sales": [{
"manager": "alberic",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "USA",
"percent-seller": "30",
"antiquity": "June 2017",
"date": "6"
}, {
"manager": "support",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "UK",
"percent-seller": "20",
"antiquity": "June 2017",
"date": "2"
},
]
};
var matchedElements = data.sales.filter(function(element) {
return (element.manager == 'support' && element.date == '2');
});
console.log(matchedElements);
//if you want to access surgeon of first element of matchedElements
console.log(matchedElements[0].surgeon);
//if you want to access surgeon of all elements in matchedElements
for(i in matchedElements)
{
console.log(matchedElements[i].surgeon);
}

You filter the sales array.
Make sure to add the polyfill from the above link if you want to support older browsers.
var matchingSales = jsonData.sales.filter(function(sale) {
return sale.manager == 'support' && sale.date == '2';
});

var data = {
"sales": [{
"manager": "alberic",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "USA",
"percent-seller": "30",
"antiquity": "June 2017",
"date": "6"
}, {
"manager": "support",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "UK",
"percent-seller": "20",
"antiquity": "June 2017",
"date": "2"
}]
};
$.each(data.sales, function(i, v) {
if (v.manager == 'support' && v.date == '2') {
console.log(v.manager)
console.log(v.surgeon)
console.log(v.amount)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Iterate over them using .each()

Related

Sort JSON by pre-defined set of keys in javascript

Lets suppose I have a JSON ListA:
LIST A
[
{
"address": "wellington lane",
"age": "23",
"country": "Australia",
"name": "Mike",
"profession": "Lawyer"
},
{
"address": "Street 25",
"age": "26",
"country": "New Zealand",
"name": "Parks",
"profession": "Engineer"
},
{
"address": "North cross",
"age": "29",
"country": "Korea",
"name": "Wanda",
"profession": "Doctor"
}
]
LIST B
["name","age","address","country","profession"]
The requirement is I need to sort the JSON LIST A according to the array LIST B and the output should look like:
[
{
"name": "Mike",
"age": "23",
"address": "wellington lane",
"country": "Australia",
"profession": "Lawyer"
},
{
"name": "Parks",
"age": "26",
"address": "Street 25",
"country": "New Zealand",
"profession": "Engineer"
},
{
"name": "Wanda",
"age": "29",
"address": "North cross",
"country": "Korea",
"profession": "Doctor"
}
]
How can I sort this out? I have tried this solution, but it seems this is not working.
Ciao, you could try to iterate in both arrays and create an array result with ordered attributes like this:
let input = [
{
"address": "wellington lane",
"age": "23",
"country": "Australia",
"name": "Mike",
"profession": "Lawyer"
},
{
"address": "Street 25",
"age": "26",
"country": "New Zealand",
"name": "Parks",
"profession": "Engineer"
},
{
"address": "North cross",
"age": "29",
"country": "Korea",
"name": "Wanda",
"profession": "Doctor"
}
]
let fields = ["name","age","address","country","profession"]
let result = [];
input.forEach(el => {
let resultobj = {}
fields.forEach(fi => {
resultobj[fi] = el[fi]
})
result.push(resultobj)
})
console.log(result)
Here's a solution using map and reduce:
const arr = [
{
"address": "wellington lane",
"age": "23",
"country": "Australia",
"name": "Mike",
"profession": "Lawyer"
},
{
"address": "Street 25",
"age": "26",
"country": "New Zealand",
"name": "Parks",
"profession": "Engineer"
},
{
"address": "North cross",
"age": "29",
"country": "Korea",
"name": "Wanda",
"profession": "Doctor"
}
];
const order = ["name", "age", "address", "country", "profession"];
const newArr = arr.map(e => order.reduce((obj, key) => ({ ...obj, [key]: e[key] }), {}));
console.log(newArr);
One way to do this without having to rely on an external library:
const arr = [
{
'address': 'wellington lane',
'age': '23',
'country': 'Australia',
'name': 'Mike',
'profession': 'Lawyer',
},
{
'address': 'Street 25',
'age': '26',
'country': 'New Zealand',
'name': 'Parks',
'profession': 'Engineer',
},
{
'address': 'North cross',
'age': '29',
'country': 'Korea',
'name': 'Wanda',
'profession': 'Doctor',
},
];
const keyOrder = ['name', 'age', 'address', 'country', 'profession'];
function applyKeyOrder(obj, keyOrder) {
const res = {};
for (const key of keyOrder) {
res[key] = obj[key];
}
return res;
}
const result = arr.map(element => applyKeyOrder(element, keyOrder));
console.log(result);
Note that this assumes that all keys in the keyOrder-array actually exist in the objects, i.e. fields would get lost if they're not present in the array.
Where "LIST A" is listA and "LIST B" is listB:
const formatList = () => {
return listA.map(item => {
const res = {};
listB.map(label => {
res[label] = item[label];
})
return res;
})
};
console.log(formatList())

How to match key while pushing value into array in javascript

I want to push a value after matching id value.
I have comments JSON which has property : reply
[{
"id": "1",
"root_id": "1",
"target_id": "12",
"text": "Hello World!",
"comment_posted_by": "John",
"comment_posted_by_image": "/../../assets/images/no-user.png",
"comment_time": "2 mins ago",
"reply": [{
"id": "123",
"root_id": "1",
"target_id": "222",
"text": "Nice!"
},
{
"id": "124",
"root_id": "1",
"target_id": "222",
"text": "Good!"
}
]
},
{
"id": "2",
"root_id": "2",
"target_id": "12",
"text": "Hello RG!",
"comment_posted_by": "John",
"comment_posted_by_image": "/../../assets/images/no-user.png",
"comment_time": "2 mins ago",
"reply": [{
"id": "123",
"root_id": "1",
"target_id": "222",
"text": "Hey john how are you?"
},
{
"id": "124",
"root_id": "1",
"target_id": "222",
"text": "Hi john!"
}
]
}, {
"id": "3",
"root_id": "3",
"target_id": "12",
"text": "Thanks.",
"comment_posted_by": "John",
"comment_posted_by_image": "/../../assets/images/no-user.png",
"comment_time": "2 mins ago"
}, {
"id": "4",
"root_id": "4",
"target_id": "12",
"text": "Great.",
"comment_posted_by": "John",
"comment_posted_by_image": "/../../assets/images/no-user.png",
"comment_time": "2 mins ago"
},
{
"id": "5",
"root_id": "5",
"target_id": "12",
"text": "Welcome.",
"comment_posted_by": "John",
"comment_posted_by_image": "/../../assets/images/no-user.png",
"comment_time": "2 mins ago"
}
]
Comments and their Reply
I want to push a reply on by using below HTML code:
HTML
<div [attr.commentId]="commentData.id" class="addReplyContainer replyTextAreaContainer" style="display: none" >
<textarea (keyup.enter)="addReply($event,commenData.root_id)" [(ngModel)]="reply" style="width:100%" class="replyText commentText addReplyTextarea form-control"></textarea>
</div>
and want to push newly made reply json into array mentioned above:
var reply =
{
"id": "125",
"root_id":1,
"target_id":"222",
"text":"Great!"
}
Is there a way to do this using $.each?
I am trying below method but it is giving me error:
addReply(event, root_id)
{
let commentDataa = this.commentsData;
let replyy = this.reply;
jQuery.each(this.commentsData, function (index, value) {
if(value.root_id == root_id)
{
commentDataa.reply.push({
root_id:root_id,
target_id: "12",
text: replyy,
});
}
})
}
Error: ERROR TypeError: Cannot read property 'push' of undefined
Any guidance would be appreciated.
Thanks in ADVANCE.
You need to access the index of the commentDataa array so that you can push reply in that particular object of commentDataa[index] object.
addReply(event, root_id);
{
let commentDataa = this.commentsData;
let replyy = this.reply;
jQuery.each(this.commentsData, function (index, value) {
if (value.root_id == root_id) {
commentDataa[index].reply.push({
root_id: root_id,
target_id: '12',
text: replyy
});
}
});
}

Multidimensional sorting with underscorejs

My json structure as below;
var MyJson =
[
{
"Country": "Austria",
"SubCategory": "55",
}, {
"Country": "Brazil",
"SubCategory": "0",
}, {
"Country": "Canada",
"SubCategory": "25",
}, {
"Country": "Cyprus",
"SubCategory": "55",
}, {
"Country": "Denmark",
"SubCategory": "0",
}, {
"Country": "France",
"SubCategory": "25",
}, {
"Country": "Greece",
"SubCategory": "55",
}, {
"Country": "Hungary",
"SubCategory": "0",
}
];
I am sorting that as below;
_.sortBy(MyJson, 'SubCategory').reverse()
Result as below;
Greece : 55
Cyprus : 55
Austria : 55
France : 25
Canada : 25
Hungary : 0
Denmark : 0
Brazil : 0
My expected result as below;
Austria : 55
Cyprus : 55
Greece : 55
Canada : 25
France : 25
Brazil : 0
Denmark : 0
Hungary : 0
I have tried as below;
_.sortBy(_.sortBy(MyJson, 'SubCategory').reverse(),'Country');
is there any way to sort json as desc, asc with underscore? I am not using Lodash because of restriction of my development environment.
Thank you in advance.
Plain Javascript approach.
var data = [{ Country: "Austria", SubCategory: "55" }, { Country: "Brazil", SubCategory: "0" }, { Country: "Canada", SubCategory: "25" }, { Country: "Cyprus", SubCategory: "55" }, { Country: "Denmark", SubCategory: "0" }, { Country: "France", SubCategory: "25" }, { Country: "Greece", SubCategory: "55" }, { Country: "Hungary", SubCategory: "0" }];
data.sort(function (a, b) {
return b.SubCategory - a.SubCategory || a.Country.localeCompare(b.Country);
});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Using underscore as stated: you can sort twice:
_(MyJson).chain().sortBy('Country').reverse().sortBy('SubCategory').reverse().value();
This answers is what you are looking for.
Here is stated one thing from underscore docs - sortBy is a stable algorithm.
That means you can first sort by your second property to put those in the correct order, and then sort by the first property - this will leave two fields with same value for the sorted property in the same order as found. (that order you already set with the first sort)
var MyJson =
[
{
"Country": "Austria",
"SubCategory": "55",
}, {
"Country": "Brazil",
"SubCategory": "0",
}, {
"Country": "Canada",
"SubCategory": "25",
}, {
"Country": "Cyprus",
"SubCategory": "55",
}, {
"Country": "Denmark",
"SubCategory": "0",
}, {
"Country": "France",
"SubCategory": "25",
}, {
"Country": "Greece",
"SubCategory": "55",
}, {
"Country": "Hungary",
"SubCategory": "0",
}
];
var sortedArray = _(MyJson).chain().sortBy('Country').reverse().sortBy('SubCategory').reverse().value();
console.log(sortedArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>

How do I create sub arrays from a JSON object

I have a JSON object as show here:
[
{
"ID": "1",
"Country": "India",
"Value1": "100",
"Value2": "200"
},
{
"ID": "2",
"Country": "China",
"Value1": "230",
"Value2": "800"
}
]
This is the result that I am looking for:
[
['India', 100],
['China', 230],
]
I tried using Jquery $.map function but was unable to get what exactly I wanted. Any pointers would be appreciated.
You can use map function :
var arr = [
{
"ID": "1",
"Country": "India",
"Value1": "100",
"Value2": "200"
},
{
"ID": "2",
"Country": "China",
"Value1": "230",
"Value2": "800"
}
];
console.log(arr.map(country=>[country.Country, country.Value1]));
This is the code that got me what I wanted:
var testJSON=[];
for(i=0;i<data.length;i++){
testJSON.push([data[i].Country,data[i].Value1])
}
Try this :
var arr = [
{
"ID": "1",
"Country": "India",
"Value1": "100",
"Value2": "200"
},
{
"ID": "2",
"Country": "China",
"Value1": "230",
"Value2": "800"
}
];
var res = arr.map(function(item) {
return [item.Country,item.Value1];
})
console.log(res);
Output :
Working fiddle : https://jsfiddle.net/h6kxvcys/
as i understand your question you want to create make object inside object.here i modify rohith's json structure .try this .i wish you will got correct answer from this.
Try this:
var arr = [{
"ID": {
"name":"Allan" ,
"sid":"1"
},
"Country": "India",
"Value1": "100",
"Value2": "200"},{
"ID": {
"name":"Brian" ,
"sid":"2"
},
"Country": "China",
"Value1": "230",
"Value2": "800"}];
Out put:

how to run ng-repeat or forEach of angular on complex json

I have a situation where I'm getting list of complex JSON data(nested type).I'm new to AngularJS, not getting solution to run ng-repeat or forEach over that.
My returned data is like below.
[{
"studPersonalDetails": {
"id": 0,
"name": "Digvijay",
"middleName": "",
"lastName": "Singh",
"fatherName": "abac",
"motherName": "abc",
"dob": "5/7/1990 12:00:00 AM"
},
"clients": {
"clientID": 1,
"clientName": null,
"clientDescriptions": null
},
"studentAddress": {
"address1": "12",
"address2": "12",
"city": "21",
"state": "212",
"pin": 2
},
"courseDetails": {
"courseID": 12,
"courseName": "12",
"courseDetail": null
},
"studentContacts": {
"email": "12",
"alternatePhone": "12",
"phone": "qw"
}
}, {
"studPersonalDetails": {
"id": 0,
"name": "Anil",
"middleName": "kumar",
"lastName": "Sharma",
"fatherName": "bac",
"motherName": "bac",
"dob": "2/11/1989 12:00:00 AM"
},
"clients": {
"clientID": 1,
"clientName": null,
"clientDescriptions": null
},
"studentAddress": {
"address1": "21",
"address2": "21",
"city": "5456",
"state": "8",
"pin": 7
},
"courseDetails": {
"courseID": 58,
"courseName": "58",
"courseDetail": null
},
"studentContacts": {
"email": "12",
"alternatePhone": "12",
"phone": "abc"
}
}]
This is the response returned by API.
Any help would be appreciated!Thanks!!
You can try something like this:
JSFiddle.
<div ng-repeat="currentRow in data">
<span>{{currentRow.studPersonalDetails.name}}</span>
<span>{{currentRow.studPersonalDetails.lastName}}</span>
</div>
$scope.arr = [{
"studPersonalDetails": {
"id": 0,
"name": "Digvijay",
"middleName": "",
"lastName": "Singh",
"fatherName": "Shyam Bahadur Singh",
"motherName": "ramawati Devi",
"dob": "5/7/1990 12:00:00 AM"
},
"clients": {
"clientID": 1,
"clientName": null,
"clientDescriptions": null
},
"studentAddress": {
"address1": "12",
"address2": "12",
"city": "21",
"state": "212",
"pin": 2
},
"courseDetails": {
"courseID": 12,
"courseName": "12",
"courseDetail": null
},
"studentContacts": {
"email": "12",
"alternatePhone": "12",
"phone": "qw"
}
}, {
"studPersonalDetails": {
"id": 0,
"name": "Anil",
"middleName": "kumar",
"lastName": "Sharma",
"fatherName": "bac",
"motherName": "bac",
"dob": "2/11/1989 12:00:00 AM"
},
"clients": {
"clientID": 1,
"clientName": null,
"clientDescriptions": null
},
"studentAddress": {
"address1": "21",
"address2": "21",
"city": "5456",
"state": "8",
"pin": 7
},
"courseDetails": {
"courseID": 58,
"courseName": "58",
"courseDetail": null
},
"studentContacts": {
"email": "12",
"alternatePhone": "12",
"phone": "abc"
}
}]
Using angular.forEach you can do it like this.
angular.forEach($scope.arr,function(value,key){
console.log(value.studPersonalDetails.lastName);
})
Using ng-repeat,you can do it like this.
<tr ng-repeat="oneArr in arr">
<td> {{oneArr.studPersonalDetails.name}}</td>
</tr>
Here is the plunker
You can see an angular ngRepeat example with your data here
First, create a controller with your data:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.datalist = [
{
"studPersonalDetails":{
"id":0,
"name":"Digvijay",
"middleName":"",
"lastName":"Singh",
"fatherName":"Shyam Bahadur Singh",
"motherName":"ramawati Devi",
"dob":"5/7/1990 12:00:00 AM"
},
"clients":{
"clientID":1,
"clientName":null,
"clientDescriptions":null
},
"studentAddress":{
"address1":"12",
"address2":"12",
"city":"21",
"state":"212",
"pin":2
},
"courseDetails":{
"courseID":12,
"courseName":"12",
"courseDetail":null
},
"studentContacts":{
"email":"12",
"alternatePhone":"12",
"phone":"qw"
}
},
{
"studPersonalDetails":{
"id":0,
"name":"Anil",
"middleName":"kumar",
"lastName":"Sharma",
"fatherName":"bac",
"motherName":"bac",
"dob":"2/11/1989 12:00:00 AM"
},
"clients":{
"clientID":1,
"clientName":null,
"clientDescriptions":null
},
"studentAddress":{
"address1":"21",
"address2":"21",
"city":"5456",
"state":"8",
"pin":7
},
"courseDetails":{
"courseID":58,
"courseName":"58",
"courseDetail":null
},
"studentContacts":{
"email":"12",
"alternatePhone":"12",
"phone":"abc"
}
}
];
}
Then attach this controller to your view and use the ngRepeat to extract each top-level object from dataList array (during the itaration the current object has alias data)
Inside the repeat statement you can display requested values accessing the data object using dot notation:
<div ng-controller="MyCtrl">
<div class="row" ng-repeat="data in datalist">
<p><span>Name</span> {{ data.studPersonalDetails.name }}</p>
<p><span>CourseID</span> {{ data.courseDetails.courseID }}</p>
</div>
</div>

Categories