How to get nodes of Json using jquery? - javascript

I have a JSON and i want to get its node under a Node, but net getting how cani get it: Here is the JSON:
{
"price": {
"VPO": 125,
"MSRP": 129.99,
"ONSALE": 99.97,
"a_bucks": 3.75
},
"short_info": {
"product_name": "MARMOT PRECIP JACKET",
"category": "WOMEN'S",
"weight": {
"lbs": 0.6,
"kg": 0.27
},
"SKU": "KNXSU921",
"part_info": "#46200",
"rating": 4,
"out_of_stock": false
},
"product_variants": {
"XS": {
"Arctic Navy": {
"InStock": true,
"Colorcode": "HMN",
"InStore": {
"NANAIMO": {
"value": "true",
"code": "154"
}
}
},
"Black": {
"InStock": true,
"Colorcode": "HMN",
"InStore": {
"NANAIMO": {
"value": "true",
"code": "154"
}
}
},
"Blue Sea": {
"InStock": true,
"Colorcode": "HMN",
"InStore": {
"NANAIMO": {
"value": "true",
"code": "154"
}
}
},
}
}
}
I want to get Elements's (Nodes) name under XS, i.e. "Arctic Navy", "Black", "Blue Sea" etc.
I have used following code:
$.each(dataObj.product_variants.XS, function (i, item) {
alert(item)
});
But not getting how can i get the required output. Please help.
Thanks in advance.

You don't need jQuery for this. You can use normal JavaScript:
Object.keys(dataObj.product_variants.XS)
This will return an array of the keys. e.g.
[ "Arctic Navy", "Black", "Blue Sea" ]

You can try
$.each(dataObj.product_variants.XS, function (i, item) {
alert(i)
});
It can be achieved through javascript also
for(var i in dataObj.product_variants.XS) {
alert(i)
});
If your dataObj.product_variants.XS would have been array, i would have been index of the element.

Try the following:
Use Object.keys() to get the keys of a object
var keys = Object.keys(dataObj.product_variants.XS);
https://jsfiddle.net/zeoj9xd8/

try
$.each(Object.keys(obj.product_variants.XS), function (i, item) {
alert(item)
});
https://jsfiddle.net/qejss4yj/

Related

Push parent arrays element and chidren array into new array in javascript

"items": {
"hotdrinks": [
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 20,
"name": "Tea",
"img": "../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 25,
"name": "Coffee",
"img": "../assets/img/Hot Drinks/2_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 50,
"name": "Hot Milk",
"img": "../assets/img/Hot Drinks/3_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 70,
"name": "Horlicks",
"img": "../assets/img/Hot Drinks/4_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 80,
"name": "Badam Milk",
"img": "../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
],
}
json i want to achieve using javascript. im just new to handling arrays and objects. thanksfound the answer given by Jeeva which works perfectly
future answers are welcome since we can know diffferent methods to achieve the same json object
dataArray = [
{title:"Hotdrinks",
content: [{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 20,
"name": "Tea",
"img": "../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 80,
"name": "Badam Milk",
"img": "../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
]}
You can use like this. This can be achieved by iterating the object.
const data = {
"items":{
"hotdrinks":[
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":20,
"name":"Tea",
"img":"../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":25,
"name":"Coffee",
"img":"../assets/img/Hot Drinks/2_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":50,
"name":"Hot Milk",
"img":"../assets/img/Hot Drinks/3_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":70,
"name":"Horlicks",
"img":"../assets/img/Hot Drinks/4_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":80,
"name":"Badam Milk",
"img":"../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
]
}
}
var dataArray = []
for(k in data.items){
var dataObj = {}
dataObj.title = k
dataObj.content = data.items[k] //You can also access the object values by using bracket ([]) notation
dataArray.push(dataObj)
}
console.log(JSON.stringify(dataArray))
The above expected output json is not valid. We can achieve the following.
[{"title":"Hotdrinks"}, {"content": [
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":20,
"name":"Tea",
"img":"../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":25,
"name":"Coffee",
"img":"../assets/img/Hot Drinks/2_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":50,
"name":"Hot Milk",
"img":"../assets/img/Hot Drinks/3_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":70,
"name":"Horlicks",
"img":"../assets/img/Hot Drinks/4_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":80,
"name":"Badam Milk",
"img":"../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
]}]
If you are okay with this then i'll give you the sample code for the same.

Filtering subarray of objects

I need to filter a subarray of elements.
var university = {
"fax": "123345",
"email": "test#test.com",
"url": "www.test.com",
"classes": [
{
"number": "1",
"name": "maths",
"students": [
{
"name": "Max",
"exams": [
{
"date": "2016-01-04T18:32:43.000Z",
"passed": false
},
{
"date": "2016-01-04T18:32:43.000Z",
"passed": true
},
{
"date": "2016-01-04T18:32:43.000Z",
"passed": false
},
{
"date": "2016-01-04T18:32:43.000Z",
"passed": true
}
]
},
{...}
]
},
{...}
]
}
Ok I need to get all the classes without filtering, all the students of each class without filtering, but in the exams array I only need to get the ones that passed.
I tried the following:
university.classes.students.exams.filter(function (el) {
return el.passed
});
But it is not working...
I've googled a solution to this without success...any help would be appreciated.
classes and students are arrays - so you have to loop those as well:
university.classes.forEach(function(uniClass) {
uniClass.students.forEach(function(student) {
student.exams = student.exams.filter(function (el) {
return el.passed;
});
});
});

push the object to array, according to order number in javascript

Below array i have 5 objects, with random order value, need to arrange the array as per the order key in object
i want push each object another array as per order.
var array = [
{
"name": {
"text": "javascript"
},
"order": {
"text": "4"
}
},
{
"name": {
"text": "angualr js"
},
"order": {
"text": "2"
}
},
{
"name": {
"text": "Ios"
},
"order": {
"text": "3"
}
},
{
"name": {
"text": "PHP"
},
"order": {
"text": "5"
}
}, {
"name": {
"text": "C"
},
"order": {
"text": "5"
}
}
]
can any explain how to follow the logic.
Just sort the array with Array.prototype.sort, it accepts a function as parameter to compare two items.
array.sort(function(a, b) {
return parseInt(a.order.text, 10) - parseInt(b.order.text, 10);
});

Issue with converting JS object to array

Here is the one which i am trying to achieve.
I have the below JSON response. I am using $.getJSON method to loads JSON data and adding it in the collection by checking whether it is array as below.
{
"r": [{
"IsDefault": false,
"re": {
"Name": "Depo"
},
"Valid": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
}, {
"Name": "Jack",
"Rate": 0.55
}, {
"Name": "Mcd",
"Rate": 0.01,
}],
},
{
"IsDefault": false,
"re": {
"Name": "Depo"
},
"Valid": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
}, {
"Name": "Jack",
"Rate": 0.55
}, {
"Name": "Mcd",
"Rate": 0.01,
}],
},
{
"IsDefault": false,
"re": {
"Name": "Depo"
},
"Valid": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
}, {
"Name": "Jack",
"Rate": 0.55
}, {
"Name": "Mcd",
"Rate": 0.01,
}],
}]
}
I am passing the json responses on both loadFromJson1 and loadFromJson2 function as parameter as below.
var tablesResult = loadFromJson1(resultstest.r[0].Clg);
loadFromJson1 = function (input) {
if (_.isArray(input)) {
alert("loadFromJson1: Inside array function");
var collection = new CompeCollection();
_.each(input, function (modelData) {
collection.add(loadFromJson1(modelData));
});
return collection;
}
return new CompeModel({
compeRates: loadFromJson2(input),
compName: input.Name
});
};
loadFromJson2 = function (input)
// here is the problem, the 'input' is not an array object so it is not going to IF condition of the isArray method. Hence i am trying to convert into array object.
{
if (_.isArray(input)) {
alert("loadFromJson2: Inside array function");
//alert is not coming here though it is array
var rcollect = new rateCollection();
_.each(input, function (modelData) {
rcollect.add(modelData);
});
return rcollect;
}
};
The above code i am passing json responeses for both loadFromJson1 and loadFromJson2 function as "input". isArray is getting true on only loadFromJson1 function and giving alert inside the if condition but not coming in loadFromJson2 function though i am passing the same parameter.
can you please tell me what mistakes i am doing here?
Your code is a bit scattered and the function loadFromJson1 is duplicted. Also some objects are not posted in de question.
I did however created a fiddle which work; "Inside array function" is printed...
simpliefied version of loadFromJson1 which is working in the fiddle:
loadFromJson1 = function (input) {
var resArray = $.map(input, function (value, index) {
return [value];
});
if (_.isArray(resArray)) {
console.log("Inside array function");
}
};

getJSON displays [object Object] rather than actual values

I have a JSON and I need to get this JSON and put in the html as a ul li list. It gets the value as object and displays [object Object] in html. If I modify the json then it works. so there is probably something wrong in my script where I am not able to loop throught he json file properly. Can some one help please:
MY JSON IS:
[
{
"us":"USA"
},
{
"fr":"FRANCE"
},
{
"es":"Spain"
},
{
"sa":"South Africa"
}
]
AND JS IS
<script>
$.getJSON('jsonfile', function(data) {
var items = [];
$.each(data ,function(key,val) {
items.push('<li id="'+ key +'">' + val +'</li>');
});
$('<ul />' , {
'class':'new-div',
html:items.join('')
}).appendTo('body');
});
</script>
UPDATED JSON:
[
{
"items":
{
"item":
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
]
}
}
]
The data you're looping over is the array, which has objects. So your key will be 0, 1, etc., and the val will be the object at that position in the array.
Your JSON structure actually makes it a bit of a pain to output, because each of your objects only has one property, but the property name varies from object to object. You can do it, by looping over the object properties even though there's only one of them:
var items = [];
$.each(data ,function(outerKey, outerVal) { // <== Loops through the array
$.each(outerVal, function(key, val) { // <== "Loops" through each object's properties
items.push('<li id="'+ key +'">' + val +'</li>');
});
});
...but I'd change the JSON structure instead. For instance, assuming the keys are unique, your original code would work with this structure:
{
"us":"USA",
"fr":"FRANCE",
"es":"Spain",
"sa":"South Africa"
}

Categories