I have a JSON object:
var json = {"Mike":1, "Jake":1, "Henry":1};
I am trying to loop through this list to access the names. Currently I am using:
for (var name in json) {
if (json.hasOwnProperty(name)) {
console.log(name);
}
}
But it's not printing the name. Is that the correct way to do it?
jsFiddle: http://jsfiddle.net/bKwYq/
As other people mentioned, this is not JSON, it's just an object.
The hasOwnProperty thing may not really be necessary here also.
var persons = {"Mike":1, "Jake":1, "Henry":1};
for (var name in persons) {
alert(name);
}
This will work in every browser: http://jsfiddle.net/HsNMY/
It can be done by getting the key using Object.keys and then using foreach loop to print to console or display as alert message.
var persons = {"Mike":1, "Jake":1, "Henry":1};
var keysInPerson= Object.keys (persons);
keysInPerson.forEach ((name) => console.log (name));
//Alert
keysInPerson.forEach ((name) => alert (name));
The correct way to PRINT the name is to use document.write instead of console.log, as in this fiddle :
http://jsfiddle.net/jRAna/
Related
Still newbie #this, hope not a silly question.
I get from a java backend a json.
For this question I assigned a with that json string.
let a={"status":"ok","data":[{"blablaMOUTI blablaDAN":"","blablaDAA blablaALHAZO":"","blablaMAR blablaBDAN":"","blablaHIM blablaDAN":""}]};
let b=a.data;
let s="";
for (i in b) {s += b[i]};
$('#msg').html(s);
As output I get object Object (small capital, big capital)
In the end I need to run over "data' and print or store that keynames : blablaMOUTI blablaDAN , blablaDAA blablaALHAZO ... on screen or in a simple array list.
The values after the keynames or a empty string, that's fine, I need only the keynames.
Found some semi simular questions, but I don't get it to work. The answers I found all trust I know already the keynames.
You can do it like this:
let a={"status":"ok","data":[{"blablaMOUTI blablaDAN":"","blablaDAA blablaALHAZO":"","blablaMAR blablaBDAN":"","blablaHIM blablaDAN":""}]};
var keys = [];
for(i = 0; i< a.data.length; i++){
for(var k in a.data[i]) {
keys.push(k);
}
}
console.log(keys)
For testing purpose this will populate an array with keys that you wanted, but you can manipulate the result as you wish
Object.getOwnPropertyNames(a.data[0]);
Output: ["blablaMOUTI blablaDAN", "blablaDAA blablaALHAZO", "blablaMAR blablaBDAN", "blablaHIM blablaDAN"]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames
Try this:
Object.getOwnPropertyNames(a.data[0]);
Output: ["blablaMOUTI blablaDAN", "blablaDAA blablaALHAZO", "blablaMAR blablaBDAN", "blablaHIM blablaDAN"]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames
The Problem is the following:
I have a JSON file that has objects with the following name: "item0": { ... }, "item1": { ... }, "item2": { ... }. But I can't access them when going through an if method.
What I've done so far:
$.getJSON('/assets/storage/items.json', function(data) {
jsonStringify = JSON.stringify(data);
jsonFile = JSON.parse(jsonStringify);
addItems();
});
var addItems = function() {
/* var declarations */
for (var i = 0; i < Object.keys(jsonFile).length; i++) {
path = 'jsonFile.item' + i;
name = path.name;
console.log(path.name);
console.log(path.type);
}
}
If I console.log path.name it returns undefined. But if I enter jsonFile.item0.name it returns the value. So how can I use the string path so that it's treated like an object, or is there an other way on how to name the json items.
As others stated 'jsonFile.item' + i is not retrieving anything from jsonFile: it is just a string.
Other issues:
It makes no sense to first stringify the data and then parse it again. That is moving back and forth to end up where you already were: data is the object you want to work with
Don't name your data jsonFile. It is an object, not JSON. JSON is text. But because of the above remark, you don't need this variable
Declare your variables with var, let or const, and avoid global variables.
Use the promise-like syntax ($.getJSON( ).then)
Iterate object properties without assuming they are called item0, item1,...
Suggested code:
$.getJSON('/assets/storage/items.json').then(function(data) {
for (const path in data) {
console.log(data[path].name, data[path].type);
}
});
What you want is to use object notation using a dynamic string value as a key instead of an object key. So, instead of using something like object.dynamicName you either have use object[dynamicName].
So in your example it would be like this.
path = 'item' + i;
jsonFile[path].name
I'm afraid you cannot expect a string to behave like an object.
What you can do is this:
path = `item${i}`
name = jsonFile[path].name
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}`);
});
});
I pass from php to js object. For example :
{"3199":{"name":"Ramona RONDEREGGER","mail":"mona.schlaepfer#bluewin.ch","phone":null,"hope":null
,"status":"NEW LEAD"},"3253":{"name":"Olivia
BAUMANN","mail":"oliviazurfluh#gmail.com","phone":null,"hope"
:null,"status":"NEW LEAD"}}
And I want to get data from this object in js (get 3199, 3253 and their data (name,mail ...).
How can I do it?
I try it:
$(data).each(function(key,value){
$(value).each(function(key,value){
console.log(value);
});
});
But id doesn't work
Please, help me to solve this problem
Thanks
Iterate through your object and get data by key. Here is the example of your dataset showed that how can you access the data in your result object.
var data = {"3199":{"name":"Ramona RONDEREGGER","mail":"mona.schlaepfer#bluewin.ch","phone":null,"hope":null
,"status":"NEW LEAD"},
"3253":{"name":"Olivia BAUMANN","mail":"oliviazurfluh#gmail.com","phone":null,"hope"
:null,"status":"NEW LEAD"}};
for(x in data){
// this will print your key
console.log("this is your key " + x);
// this line will print your key object
console.log(data[x]);
//to access internal element
console.log(data[x]['mail']);
}
Specify key like this value["3199"]
var data = {"3199":{"name":"Ramona RONDEREGGER","mail":"mona.schlaepfer#bluewin.ch","phone":null,"hope":null,"status":"NEW LEAD"},"3253":{"name":"Olivia BAUMANN","mail":"oliviazurfluh#gmail.com","phone":null,"hope"
:null,"status":"NEW LEAD"}};
$(data).each(function(key,value){
$(value).each(function(key,value){
console.log(value["3199"]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];