Object.keys(data).forEach does not loop - javascript

I try to to get a value form json object.
var data={
"1":[{"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}],
"2":[{"departmentID":2,"departmentName":"HR","branchId":2,"branchName":"DEF"}]
};
Object.keys(data).forEach(function(element, key, _array) {
console.log("branchId: "+element+" "+"BranchName : "+data[element][key].branchName)
for(dept of data[element]) {
console.log("Department name : "+dept.departmentName)
}
});
Here output is : the first result only and throws branchName is undefined exception.
But if the json object has multi object,its working fine.
var data={
"1":[{"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}],
"2":[{"departmentID":2,"departmentName":"HR","branchId":2,"branchName":"XYZ"},
{"departmentID":3,"departmentName":"Food","branchId":2,"branchName":"XYZ"}]
}
I think, since I'm new to javascript, I couldn't solve. I tried a lot of reference to solve this problem, but I could not. Please try to solve this. Thanks in advance.

he first result only and throws branchName is undefined exception.
You need to replace
data[element][key].branchName
with
data[element][0].branchName
Because
element is the key "1",
so data[element] becomes [{"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}],
data[element][0] becomes {"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}
finally data[element][0].branchName is "ABC"

You have something mixed with your keys and indexes.
You can use Object.values (ES8 only) to get exact the values and left the keys part. Then iterate over them and make your strings.
const data = {
"1":[{"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}],
"2":[{"departmentID":2,"departmentName":"HR","branchId":2,"branchName":"DEF"}]
}
Object.values(data).forEach(function(values) {
values.forEach(value => {
console.log(`branchId: ${value.branchId} BranchName: ${value.branchName} Department Name: ${value.departmentName}`);
});
});

Related

JSON.parse does not convert Stringified JSON Array

[
{ comicid: "5f55e91271b808206c132d7c", purchasetype: "pb_single" }
]
Above is my JSON Array that is stringified,I tried to JSON.parse and other functions like iterating it in a for loop but the key values also got scrambled.
Is there any way or an npm method that could instantly output the retrieved variable?
var cartItemFromLocalStorage = JSON.parse(localStorage.getItem("cartitem"));
if (cartItemFromLocalStorage != null) {
console.log("It came defined");
console.log("This is OG Array: " + cartItemFromLocalStorage);
let cartItemObject = {
//set object data
comicid: this.state.comicId,
purchasetype: this.state.purchaseType,
};
console.log(cartItemObject);
cartItemFromLocalStorage.push(cartItemObject);
localStorage.setItem("cartitem", result); //localstorage only supports strings
toast.success("Item Added to cart");
}
I checked the consoles and the states are putting up the data correctly.
I'm an extreme beginner in react js, help is much appreciated
The "JSON" you have written is actually JavaScript, not JSON. To convert it JSON use the JSON.stringify function, like so
> JSON.stringify([
{ comicid: "5f55e91271b808206c132d7c", purchasetype: "pb_single" }
]);
'[{"comicid":"5f55e91271b808206c132d7c","purchasetype":"pb_single"}]'
and then replace the value in localStorage with it.
Even easier would be to type into the developer console
localStorage.setItem("cartitem", JSON.stringify([
{ comicid: "5f55e91271b808206c132d7c", purchasetype: "pb_single" }
]));

Javascript: How to account for undefined JSON which breaks for loop

I am having trouble and may be approaching this wrong so open to other solutions. From a fetch call, I am receiving a larger json array of objects which has further nesting in each object. I want to slim down the larger object array to only some values (for each object) and I am currently doing that by iterating over all of the objects in the larger array and taking the values I want from each object and then pushing to a newly created larger array. The below code works sometimes, however there are times where no data is present in some of the values from the json breaking my for loop. For exampledata.products[i].images[0].src in a given object is sometimes undefined, which breaks the loop saying "cant read property .src of undefined" and doesn't iterate all the way through.
Main questions?
1. How can I account for undefined values in any given key:value pair without breaking the loop
2. Is there a better way to go about this entirely?
I can edit the answer to include an example of the incoming json if that helps at all
Edit
I also want to not include any object which resulted in undefined image in the final array. Is there any way to prevent that object from being added or maybe filter it out later?
let productFilter = []
fetch('https://some.json')
.then(
function (response) {
response.json().then(function (data) {
for (var i = 0; i < data.products.length; i++) {
let filteredArray = {
"productId": data.products[i].id,
"productName": data.products[i].title,
"productImg": data.products[i].images[0].src
}
productFilter.push(filteredArray)
}
});
}
)
.catch(function (err) {
console.log('Fetch Error', err);
})
use a conditional expression:
"productImg": data.products[i].images[0] ? data.products[i].images[0].src : "put default image URL here"
If you don't want these objects in the array at all, just put a test around the entire code that adds the object.
if (data.products[i].images[0]) {
let filteredArray = {
"productId": data.products[i].id,
"productName": data.products[i].title,
"productImg": data.products[i].images[0].src
}
productFilter.push(filteredArray)
}
For exampledata.products[i].images[0].src in a given object is sometimes undefined, which breaks the loop saying "cant read property .src of undefined"
The error tells you that exampledata.products[i].images[0] is undefined, not exampledata.products[i].images[0].src itself. To deal with this, you can add a simple if statement inside your for loop:
let filteredArray = {
"productId": data.products[i].id,
"productName": data.products[i].title,
}
if (exampledata.products[i].images[0]) {
filteredArray.productImg = exampledata.products[i].images[0].src
}
Note that this solution will leave out the productImg key when there is no image. Alternatively, you can use Barmar's answer if you want to ensure the key always exists and have an appropriate default, whether it is a default URL or just undefined.
Suggestions:
Use a variable to shorten many lines in your code:
product = exampledata.products[i];
Now you can do product.id, etc.
Check out the map() function of Array. You can do the same thing you are doing here without writing all of the boilerplate code for the for loop.
You need to check if data.products[i] exists, otherwise you're attempting to reference properties of an undefined object. The same logic applies for the lower level reference to images[0].src
let productFilter = []
fetch('https://some.json')
.then(
function (response) {
response.json().then(function (data) {
for (var i = 0; i < data.products.length; i++) {
if (data.products[i]) {
let filteredArray = {
"productId": data.products[i].id,
"productName": data.products[i].title,
// "productImg": data.products[i].images[0].src
}
if (data.products[i].images[0]) {
filteredArray.productImg = data.products[i].images[0].src;
}
productFilter.push(filteredArray)
}
}
});
}
)
.catch(function (err) {
console.log('Fetch Error', err);
})

Counting records in JSON array using javascript and Postman

I have a control that returns 2 records:
{
"value": [
{
"ID": 5,
"Pupil": 1900031265,
"Offer": false,
},
{
"ID": 8,
"Pupil": 1900035302,
"Offer": false,
"OfferDetail": ""
}
]
}
I need to test via Postman, that I have 2 records returned. I've tried various methods I've found here and elsewhere but with no luck. Using the code below fails to return the expected answer.
responseJson = JSON.parse(responseBody);
var list = responseBody.length;
tests["Expected number"] = list === undefined || list.length === 2;
At this point I'm not sure if it's the API I'm testing that's at fault or my coding - I've tried looping through the items returned but that's not working for me either. Could someone advise please - I'm new to javascript so am expecting there to be an obvious cause to my problem but I'm failing to see it. Many thanks.
In postman, under Tests section, do the following (screenshot below):
var body = JSON.parse(responseBody);
tests["Count: " + body.value.length] = true;
Here is what you should see (note: I replaced responseBody with JSON to mock up example above):
Correct your json. and try this.
=======================v
var test = JSON.parse('{"value": [{"ID": 5,"Pupil": 1900031265,"Offer": false},{"ID": 8,"Pupil": 1900035302,"Offer": false,"OfferDetail": ""}] }')
test.value.length; // 2
So you need to identify the array in the json (starting with the [ bracket. and then take the key and then check the length of the key.
Here's the simplest way I figured it out:
pm.expect(Object.keys(pm.response.json()).length).to.eql(18);
No need to customize any of that to your variables. Just copy, paste, and adjust "18" to whatever number you're expecting.
This is what I did for counting the recods
//parsing the Response body to a variable
responseJson = JSON.parse(responseBody);
//Finding the length of the Response Array
var list = responseJson.length;
console.log(list);
tests["Validate service retuns 70 records"] = list === 70;
More updated version of asserting only 2 objects in an array:
pm.test("Only 2 objects in array", function (){
pm.expect(pm.response.json().length).to.eql(2);
});
Your response body is an object you cannot find the length of an object try
var list = responseJson.value.length;
First of all you should convert response to json and find value path. Value is array. You should call to length function to get how many objects in there and check your expected size
pm.test("Validate value count", function () {
pm.expect(pm.response.json().value.length).to.eq(2);
});
I had a similar problem, what I used to test for a certain number of array members is:
responseJson = JSON.parse(responseBody);
tests["Response Body = []"] = responseJson.length === valueYouAreCheckingFor;
To check what values you're getting, print it and check the postman console.
console.log(responseJson.length);
Counting records in JSON array using javascript and insomnia
//response insomnia
const response = await insomnia.send();
//Parse Json
const body = JSON.parse(response.data);
//Print console:
console.log(body.data.records.length);
pm.test("Only 2 objects in array", function (){
var jsonData = pm.response.json();
let event_length = jsonData.data.length;
pm.expect(event_length).to.eql(2);
});
As mentioned in the comments, you should test responseJson.value.length
responseJson = JSON.parse(responseBody);
tests["Expected number"] = typeof responseJson === 'undefined' || responseJson.value.length;
I was facing similar issue while validating the length of an array inside a JSON. The below snippet should help you resolve it-
responseJson = JSON.parse(responseBody);
var list = responseBody.length;
tests["Expected number"] = responseJson.value.length === list;
Working Code
pm.test("Verify the number of records",function()
{
var response = JSON.parse(responseBody);
pm.expect(Object.keys(response.value).length).to.eql(5);
});
//Please change the value in to.eql function as per your requirement
//'value' is the JSON notation name for this example and can change as per your JSON

Getting first object inside JSON

I'll cut straight to the chase. I'm getting a json object with another object inside of it like so:
function getName(summonerName, region) {
LolApi.Summoner.getByName(summonerName, region, function(err, summoner) {
if(!err) {
console.log(summoner);
}
});
}
However, the result of this call is (let's stay summonerName is "tetsii"):
{ tetsii:
{ id: 51520537,
name: 'tetsii',
profileIconId: 23,
summonerLevel: 23,
revisionDate: 1408307600000
}
}
Now, I can access the id's and stuff with "console.log(summoner.tetsii.id)" for example, but because the summonerName (in this case "tetsii") can be anything, I prefer not to do it like so. So, my question is: how to access the first object inside a JSON or is there another way? And no, I can't get an array in this case afaik.
I would like to note that I've tried "console.log(summoner.summonerName.id)", but that doesn't yield results as summonerName is a string.
Thanks everybody
EDIT: Got the answer. By simply using summoner[summonerName].id I am able to grab the id. Thanks everyone for answers!
-Tetsii
By using Object.keys. For example, if you know that summoner will only have a single top-level key, you can get it with:
var summonerName = Object.keys(summoner)[0];
Obligatory browser support notice: IE < 9 does not support this out of the box, but you can use a polyfill provided in the MDN page as a compatibility shim.
There is no order in objects, so there's no guarantee you'll get the object you think, but using Object.keys and shift() you can do
var first = summoner[Object.keys(summoner).shift()];
If there is no way to return it as an array, the best idea is to iterate over the object properties as documented in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
The most important part is:
for (var prop in summoner) {
console.log("summoner." + prop + " = " + summoner[prop]);
}
Tested in console:
var summoner = { tetsii:
{ id: 51520537,
name: 'tetsii',
profileIconId: 23,
summonerLevel: 23,
revisionDate: 1408307600000
}
};
yields:
summoner.tetsii = [object Object]

.each parse JSON returns undefined

Hi I have the following codes:
$.ajax({'type':'POST', 'url':'https://www.123.com/site/gethistory',
'data':{'a': this.username, 'b': username},
'success':function(history){
alert(history);
var codes = jQuery.parseJSON(history);
$.each(codes, function(key, value) {
alert(key);
}); //each
},
'error':function(){
}
}); //ajax
Right now the key is undefined. And i tried to alert(value.text), it still gives me undefined.
history is alerted as this:
[{"demo":{"text":"hi
man","time":"1380167419"},"admin":{"text":"hi","time":"1380167435"},"demo":{"text":"this
works flawless now.","time":"1380167436"},"demo":{"text":"we are
basically done with this/","time":"1380167443"}}]
It works fine in this fiddle. However, there is a problem with your JSON.
Although it is syntactically correct, it is structured such that you are returning an array of one object with a number of properties all with the same name:
[
{ "demo":{
"text":"hi man",
"time":"1380167419"
},
"admin":{
"text":"hi",
"time":"1380167435"
},
"demo":{
"text":"this works flawless now.",
"time":"1380167436"
},
"demo":{
"text":"we are basically done with this/",
"time":"1380167443"
}
}
]
Each successive demo will overwrite the previous one, so you'll only see the last demo property.
Looks like there is something wrong with your JSON. Try alert codes and make sure the parsed JSON is in the right format, i.e key/value pairs
no need to use jQuery to parse JSON. Just var codes = JSON.parse(history)
$.each(codes, function(k, v){
console.log(v )
});

Categories