How to loop through properties of a JSON object? - javascript

I am trying to loop through the properties of JSON object, but unable to do so.
var ds={
"Table": [
{
"SrNo": 1,
"AuctionName": "test auction",
"AuctionDescription": "auction desc",
"Testproject": "Y",
"State": "India",
"City": "2",
"CompanyName": "IIFL",
"Commodity": "10001",
"BaseLineSpend": "50000",
"ContractMonths": "5",
"Owner": "arbaaz",
"PreviewBids": "Y",
"PrebidEndTime": "2015-09-11T18:00:00",
"BiddingStartTime": "2015-09-10T18:00:00",
"FirstTimeRunTime": 10,
"TimeBtwLotClosing": 15,
"BidRank": "20",
"StartOverTime": 25,
"OverTime": 30,
"Buffer": "Y",
"ImproveBidBy": "PERCENTAGE",
"TieBids": "Y",
"ActiveObservers": "Babitha G-C140492,",
"Observers": "Tabrez Abdul Aziz Shaikh-A185615,",
"ProjectOwner": "Tahir - Siddiqui-C107037,Tahir Ali-C132420,",
"Administrator": "Rabi Roy-V182597,Gagan Kondalana Poonacha-C134452,Rabindra Kumar Choubey-C139454,",
"GUID": "200869b0-e6be-4642-95ec-97509e457d63",
"MkrId": "C123627",
"MkrDt": "2015-09-03T16:23:15.917",
"IsCreated": null
}
]
}
Based on other similar question on stackoverflow. I tried:
var DataSet = jQuery.parseJSON(ds);
var json_parsed = DataSet.Table;
var items = json_parsed.Items; // this is always undefined in console.
for (var i = 0; i < items.length; ++i) {
console.log("Item #" + i);
for (var name in items[i]) {
alert(name + "=" + items[i][name]);
}
}
I get undefined at json_parsed.Items; in console.
I am expecting property names to be displayed in alert eg: Srno, AuctionName .. so on.

Well, Table is an array, for a start. Second, even if you used Table[0].Items, there's no Items property, which is why you're getting "undefined".
So try this instead:
var items = json_parsed[0];
for (var name in items) {
alert(name + "=" + items[name]);
}
DEMO

I see you have jQuery in there. The Javascript approach is good. But if you want to loop through a JSON object in jQuery, then you can try following code:
var ds={
"Table": [
{
"SrNo": 1,
"AuctionName": "test auction",
"AuctionDescription": "auction desc",
"Testproject": "Y",
"State": "India",
"City": "2",
"CompanyName": "IIFL",
"Commodity": "10001",
"BaseLineSpend": "50000",
"ContractMonths": "5",
"Owner": "arbaaz",
"PreviewBids": "Y",
"PrebidEndTime": "2015-09-11T18:00:00",
"BiddingStartTime": "2015-09-10T18:00:00",
"FirstTimeRunTime": 10,
"TimeBtwLotClosing": 15,
"BidRank": "20",
"StartOverTime": 25,
"OverTime": 30,
"Buffer": "Y",
"ImproveBidBy": "PERCENTAGE",
"TieBids": "Y",
"ActiveObservers": "Babitha G-C140492,",
"Observers": "Tabrez Abdul Aziz Shaikh-A185615,",
"ProjectOwner": "Tahir - Siddiqui-C107037,Tahir Ali-C132420,",
"Administrator": "Rabi Roy-V182597,Gagan Kondalana Poonacha-C134452,Rabindra Kumar Choubey-C139454,",
"GUID": "200869b0-e6be-4642-95ec-97509e457d63",
"MkrId": "C123627",
"MkrDt": "2015-09-03T16:23:15.917",
"IsCreated": null
}
]
}
var jsonData = ds.Table[0];
$.each(jsonData, function(index, value) {
console.log( index + '=' + value);
});

Related

How to get Key and Value from JSON object in Javascript(Postman)

I have a JSON object like this, I wanna access the list array elements with key and value in postman.
{
"data": {
"total": 1,
"list": [
{
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
}
]
},
"success": true,
"message": ""
}
How to separate it as Key and Value in Javascript like,
Key: id,name,mobileNo,address,city,..
Value: 53,Sonu,6543213456,Greeny Pathway,NewYork,....
First remove comma from line : "qty": null, otherwise it will cause error in json parsing.
var resultJSON = `{
"data": {
"total": 1,
"list": [
{
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
}
]
},
"success": true,
"message": ""
}`;
var result = $.parseJSON(resultJSON);
var myList = result.data.list[0];
$.each(myList, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
you can use below codes:
const keys = Object.keys(jsonObject);
const values = Object.values(jsonObject);
But your JSON object is deep, you should flatten it and then use keys and values of Object to make them separate.
You can get using key and value separately in a array.
var a = {
"data": {
"total": 1,
"list": [
{
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null,
}
]
},
"success": true,
"message": ""
}
var keyval = Object.keys(a.data.list[0])
console.log(keyval)
var values = Object.values(a.data.list[0])
console.log(values)
JSON objects are key value pair you cannot get the keys and values in object form as you desire but you can get both in form of arrays from this code
var key = []
var values = []
list.map(function(l){ keys = Object.getOwnPropertyNames(l);
keys.map(function(key) {values.push(l[key]);})})
Finally this works for me!(In Postman Script)
var resdata = JSON.parse(responseBody);
console.log(resdata);
key = Object.keys(resdata.data.list[0]);
console.log(key);
value =Object.values(resdata.data.list[0]);
console.log(value);

Create JSON object with same keys for API call

I'm trying to create a JSON object for an API call which has the following format:
....
"Key": "Value",
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "20",
"Width": "25",
"Height": "30"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "80"
}
},
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "15",
"Width": "24",
"Height": "27"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "50"
}
},
"Key": "Value",
....
I should add as many "Package" objects as needed. However, I've tried doing this in many different ways but every time that I parse the variable to be used the first objects get overwritten and I end up with only the last object.
This is what I'm trying at the moment, still with no luck:
var lineItems = '{';
for (var i=0;i<inputObject.packages.length;i++) {
lineItems += '"Package": {"PackagingType": {"Code": "02","Description": "Rate"},"Dimensions": {"UnitOfMeasurement": {"Code": "IN","Description": "inches"},"Length": ' + inputObject.packages[i][0].toString() + ',"Width": ' + inputObject.packages[i][1].toString() + ',"Height": ' + inputObject.packages[i][2].toString() + '},"PackageWeight": {"UnitOfMeasurement": {"Code": "Lbs","Description": "pounds"},"Weight": ' + inputObject.packages[i][3].toString() + '}}';
if (i !== inputObject.packages.length-1) {
lineItems += ',';
}
}
lineItems += '}';
lineItems = JSON.parse(lineItems);
How about numbering your packages, ie:
for (var i=0;i<inputObject.packages.length;i++) {
lineItems+='"Package" + i : { ... }'
}
edit: to get required result (as an array - because it's not JSON), here's an example:
var a=[];
var b={"package": {"c":100,"d":200,"e":300}}
var c={"package": {"c":800,"d":700,"e":600}}
a.push(b);
a.push(c);
console.log(a);

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>');

Merging collections to json array

I have 2 json format, namely jsonA and jsonB, in which i would like to combine into jsonC as follow.
Appreciate if someone can tell me how to do it.
jsonA
{
"text1": "Hello",
"text2": "Hi",
"text3": "There"
}
jsonB
[
{
"id": "text1",
"category": "Big"
},
{
"id": "text2",
"category": "Medium"
},
{
"id": "text3",
"category": "Small"
},
]
Final
[
{
"id": "text1",
"category": "Big",
"message": "Hello"
},
{
"id": "text2",
"category": "Medium",
"message": "Hi"
},
{
"id": "text3",
"category": "Small",
"message": "There"
}
]
Solution for a new array.
Basically it iterates the array and build a new object for every found object. It adds a new property message with the wanted content form objectA.
var objectA = { "text1": "Hello", "text2": "Hi", "text3": "There" },
objectB = [{ "id": "text1", "category": "Big" }, { "id": "text2", "category": "Medium" }, { "id": "text3", "category": "Small" }],
objectC = objectB.map(function (a) {
return {
id: a.id,
category: a.category,
message: objectA[a.id]
};
});
document.write('<pre>' + JSON.stringify(objectC, 0, 4) + '</pre>');
Soulution for a mutated array.
This solution takes the array and adds in the loop a new property with the value from objectA.
var objectA = { "text1": "Hello", "text2": "Hi", "text3": "There" },
objectB = [{ "id": "text1", "category": "Big" }, { "id": "text2", "category": "Medium" }, { "id": "text3", "category": "Small" }];
objectB.forEach(function (a) {
a.message = objectA[a.id];
});
document.write('<pre>' + JSON.stringify(objectB, 0, 4) + '</pre>');
Firstly, You need to traverse 2nd json array. Than traverse 1st json and compare for indexing. If indexing matches then add new attribute to 2nd json.
Here is full example :
var jsonA = '{"text1": "Hello","text2": "Hi","text3": "There"}';
var jsonB = '[{"id": "text1","category": "Big"},{"id": "text1","category": "Medium"},{"id": "text1","category": "Small"}]';
jsonA = JSON.parse(jsonA);
jsonB = JSON.parse(jsonB);
for(var i=0;i<jsonB.length;i++){
for(var j in jsonA){
if(j == ("text"+(i+1))){
jsonB[i].message = jsonA[j];
}
}
}
console.log(JSON.stringify(jsonB));
Output : [{"id":"text1","category":"Big","message":"Hello"},{"id":"text1","category":"Medium","message":"Hi"},{"id":"text1","category":"Small","message":"There"}]

Check if a particular sequence of array elements is empty

["Order", "Id", "Comment", "Id_type", "UbAction", "Ub_Factor", "LbAction","Lb_Factor",
"6", "12321", "3rd test", "Industry", "0.23", "true", "0", "false",
"22", "sss", "4", "Sector", "0", "true", "0.565676", "true",
"99", "277906", "", "Sector", "1", "true", "0", "true",
"3", "416921", "correction check", "Industry", "1", "true", "0", "false"]
I have this array shown above. The first eight elements are the header. So I will remove those using splice.
I need to check if the elements 8,16,24 AND 9,17,25 AND 11,19,27 are empty. How can i loop through this elements dynamically. The sequence of elements are weird. Can someone please suggest how to check if these above element number is the current one which is being looped.
Thanks guys for the replies. I worked on it a bit and the below code worked for me pretty nicely...
var count = 0;
var array2= [0,1,3,4,6];
function checkArray5(cell_data){
for(var i=8;i<cell_data.length; i++) {
for (var j=0;j<5;j++)
{
if (i%8 == array2[j])
{
if(cell_data[i] ==="") {
console.log(count++);
}
}
}
}
}
checkArray5(array);
Use the % operator to search for the indexes that return 0, 1 and 3 respectively:
var table = ["Order", "Id", "Comment", "Id_type", "UbAction", "Ub_Factor", "LbAction","Lb_Factor",
"6", "12321", "3rd test", "Industry", "0.23", "true", "0", "false",
"22", "sss", "4", "Sector", "0", "true", "0.565676", "true",
"99", "277906", "", "Sector", "1", "true", "0", "true",
"3", "416921", "correction check", "Industry", "1", "true", "0", "false"];
var index = 0;
var columns = 8;
var cells = table.slice(columns);
var len = cells.length;
for (;index < len; index++) {
var mod = index % columns;
switch (mod) {
case 0:
case 1:
case 3:
isEmpty(cells[index]);
break;
}
}
Here is my suggestion:
var myArr = ["Order", "Id", "Comment", "Id_type", "UbAction", "Ub_Factor", "LbAction", "Lb_Factor",
"6", "12321", "3rd test", "Industry", "0.23", "true", "0", "false",
"22", "sss", "4", "Sector", "0", "true", "0.565676", "true",
"99", "277906", "", "Sector", "1", "true", "0", "true",
"3", "416921", "correction check", "Industry", "1", "true", "0", "false"];
// added or remove elements to be checked if empty.
var emptyElementChk = [8, 9, 11, 16, 17, 19, 24, 25, 27];
for (var i = 0; i < emptyElementChk.length; i++) {
//All checked array listed
console.log("Key : " + emptyElementChk[i] + " value: " + myArr[emptyElementChk[i]]);
if (myArr[emptyElementChk[i]] == "") {
// empty arrays action
} else {
// none empty arrays action
}
};

Categories