How iterate this JSON object with jQuery/regular JavaScript? - javascript

For a JSON object, how do I print all values?`
Sample:
{"firstname":{"isEmpty":"Value is required and can't be empty"},"email":{"isEmpty":"Value is required and can't be empty"}}

You can use for .. in to loop over the members of an object:
var i, obj = {{your json object}};
for (i in obj) {
if (obj.hasOwnProperty(i)) {
console.log(i + ": " + obj[i]);
}
}
Your object has nested objects inside it, so you may need to have two nested loops.

Just as if it's an associative array.
for (k in object){
//You don't need printing source codes of object methods, right?
if (typeof object[k] != 'function'){
document.write(object[k]);
}
}

A "JSON-object" is actually just a Javascript-object in text-notation. So all you have to do at clientside, is to parse that string with either well known and available methods or (slightly worse) eval that string.
Example:
var jsonString = '{"firstname":{"isEmpty":"Value is required and cannot be empty"},"email":{"isEmpty":"Value is required and cannot be empty"}}'
var myParsedObject = JSON.parse( jsonString );
for(var key in myParsedObject) {
if( myParsedObject.hasOwnProperty( key ) )
console.log(key, ': ', myParsedObject[key]);
}
JSON.parse will do exactly the above desribed. It converts the object text notation into a true Javascript object. Once that is done, we can simply loop over it's keys and access its propertys using for..in.
Doing it more "newschool'ish" we would do it with ES5, like
var myParsedObject = JSON.parse( jsonString );
Object.keys( myParsedObject ).forEach(function( key ) {
console.log(key, ': ', myParsedObject[key]);
});

Related

How to slice() return values from JSON API [duplicate]

var obj = {
name: "Simon",
age: "20",
clothing: {
style: "simple",
hipster: false
}
}
for(var propt in obj){
console.log(propt + ': ' + obj[propt]);
}
How does the variable propt represent the properties of the object? It's not a built-in method or property. Why does it come up with every property in the object?
Iterating over properties requires this additional hasOwnProperty check:
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
// do stuff
}
}
It's necessary because an object's prototype contains additional properties for the object which are technically part of the object. These additional properties are inherited from the base object class, but are still properties of obj.
hasOwnProperty simply checks to see if this is a property specific to this class, and not one inherited from the base class.
It's also possible to call hasOwnProperty through the object itself:
if (obj.hasOwnProperty(prop)) {
// do stuff
}
But this will fail if the object has an unrelated field with the same name:
var obj = { foo: 42, hasOwnProperty: 'lol' };
obj.hasOwnProperty('foo'); // TypeError: hasOwnProperty is not a function
That's why it's safer to call it through Object.prototype instead:
var obj = { foo: 42, hasOwnProperty: 'lol' };
Object.prototype.hasOwnProperty.call(obj, 'foo'); // true
As of JavaScript 1.8.5 you can use Object.keys(obj) to get an Array of properties defined on the object itself (the ones that return true for obj.hasOwnProperty(key)).
Object.keys(obj).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object
});
This is better (and more readable) than using a for-in loop.
Its supported on these browsers:
Firefox (Gecko): 4 (2.0)
Chrome: 5
Internet Explorer: 9
See the Mozilla Developer Network Object.keys()'s reference for futher information.
Girls and guys we are in 2019 and we do not have that much time for typing... So lets do this cool new fancy ECMAScript 2016:
Object.keys(obj).forEach(e => console.log(`key=${e} value=${obj[e]}`));
In up-to-date implementations of ES, you can use Object.entries:
for (const [key, value] of Object.entries(obj)) { }
or
Object.entries(obj).forEach(([key, value]) => ...)
If you just want to iterate over the values, then use Object.values:
for (const value of Object.values(obj)) { }
or
Object.values(obj).forEach(value => ...)
It's the for...in statement (MDN, ECMAScript spec).
You can read it as "FOR every property IN the obj object, assign each property to the PROPT variable in turn".
It's just a for...in loop. Check out the documentation at Mozilla.
if (typeof obj === 'object' && obj !== null) {
Object.keys(obj).forEach(key => {
console.log("\n" + key + ": " + obj[key]);
});
}
// *** Explanation line by line ***
// Explaining the bellow line
// It checks if obj is neither null nor undefined, which means it's safe to get its keys.
// Otherwise it will give you a "TypeError: Cannot convert undefined or null to object" if obj is null or undefined.
// NOTE 1: You can use Object.hasOwnProperty() instead of Object.keys(obj).length
// NOTE 2: No need to check if obj is an array because it will work just fine.
// NOTE 3: No need to check if obj is a string because it will not pass the 'if typeof obj is Object' statement.
// NOTE 4: No need to check if Obj is undefined because it will not pass the 'if type obj is Object' statement either.
if (typeof obj === 'object' && obj !== null) {
// Explaining the bellow line
// Just like in the previous line, this returns an array with
// all keys in obj (because if code execution got here, it means
// obj has keys.)
// Then just invoke built-in javascript forEach() to loop
// over each key in returned array and calls a call back function
// on each array element (key), using ES6 arrow function (=>)
// Or you can just use a normal function ((key) { blah blah }).
Object.keys(obj).forEach(key => {
// The bellow line prints out all keys with their
// respective value in obj.
// key comes from the returned array in Object.keys(obj)
// obj[key] returns the value of key in obj
console.log("\n" + key + ": " + obj[key]);
});
}
If your environment supports ES2017 then I would recommend Object.entries:
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`);
});
As shown in Mozillas Object.entries() documentation:
The Object.entries() method returns an array of a given object's own
enumerable property [key, value] pairs, in the same order as that
provided by a for...in loop (the difference being that a for-in loop
enumerates properties in the prototype chain as well).
Basically with Object.entries we can forgo the following extra step that is required with the older for...in loop:
// This step is not necessary with Object.entries
if (object.hasOwnProperty(property)) {
// do stuff
}
Dominik's answer is perfect, I just prefer to do it that way, as it's cleaner to read:
for (var property in obj) {
if (!obj.hasOwnProperty(property)) continue;
// Do stuff...
}
jquery allows you to do this now:
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
The for...in loop represents each property in an object because it is just like a for loop. You defined propt in the for...in loop by doing:
for(var propt in obj){
alert(propt + ': ' + obj[propt]);
}
A for...in loop iterates through the enumerable properties of an object. Whichever variable you define, or put in the for...in loop, changes each time it goes to the next property it iterates. The variable in the for...in loop iterates through the keys, but the value of it is the key's value. For example:
for(var propt in obj) {
console.log(propt);//logs name
console.log(obj[propt]);//logs "Simon"
}
You can see how the variable differs from the variable's value. In contrast, a for...of loop does the opposite.
I hope this helps.
To add ES2015's usage of Reflect.ownKeys(obj) and also iterating over the properties via an iterator.
For example:
let obj = { a: 'Carrot', b: 'Potato', Car: { doors: 4 } };
can be iterated over by
// logs each key
Reflect.ownKeys(obj).forEach(key => console.log(key));
If you would like to iterate directly over the values of the keys of an object, you can define an iterator, just like JavaScipts's default iterators for strings, arrays, typed arrays, Map and Set.
JS will attempt to iterate via the default iterator property, which must be defined as Symbol.iterator.
If you want to be able to iterate over all objects you can add it as a prototype of Object:
Object.prototype[Symbol.iterator] = function*() {
for(p of Reflect.ownKeys(this)){ yield this[p]; }
}
This would enable you to iterate over the values of an object with a for...of loop, for example:
for(val of obj) { console.log('Value is:' + val ) }
Caution: As of writing this answer (June 2018) all other browsers, but IE, support generators and for...of iteration via Symbol.iterator
The above answers are a bit annoying because they don't explain what you do inside the for loop after you ensure it's an object: YOU DON'T ACCESS IT DIRECTLY! You are actually only delivered the KEY that you need to apply to the OBJ:
var obj = {
a: "foo",
b: "bar",
c: "foobar"
};
// We need to iterate the string keys (not the objects)
for(var someKey in obj)
{
// We check if this key exists in the obj
if (obj.hasOwnProperty(someKey))
{
// someKey is only the KEY (string)! Use it to get the obj:
var myActualPropFromObj = obj[someKey]; // Since dynamic, use [] since the key isn't literally named "someKey"
// NOW you can treat it like an obj
var shouldBeBar = myActualPropFromObj.b;
}
}
This is all ECMA5 safe. Even works in the lame JS versions like Rhino ;)
let obj = {"a": 3, "b": 2, "6": "a"}
Object.keys(obj).forEach((item) => {console.log("item", obj[item])})
// a
// 3
// 2
You can access the nested properties of the object using the for...in and forEach loop.
for...in:
for (const key in info) {
console.log(info[key]);
}
forEach:
Object.keys(info).forEach(function(prop) {
console.log(info[prop]);
// cities: Array[3], continent: "North America", images: Array[3], name: "Canada"
// "prop" is the property name
// "data[prop]" is the property value
});
You can use Lodash. The documentation
var obj = {a: 1, b: 2, c: 3};
_.keys(obj).forEach(function (key) {
...
});
Object.keys(obj).forEach(key =>
console.log(`key=${key} value=${obj[key]}`)
);
Nowadays you can convert a standard JS object into an iterable object just by adding a Symbol.iterator method. Then you can use a for of loop and acceess its values directly or even can use a spread operator on the object too. Cool. Let's see how we can make it:
var o = {a:1,b:2,c:3},
a = [];
o[Symbol.iterator] = function*(){
var ok = Object.keys(this);
i = 0;
while (i < ok.length) yield this[ok[i++]];
};
for (var value of o) console.log(value);
// or you can even do like
a = [...o];
console.log(a);
Your for loop is iterating over all of the properties of the object obj. propt is defined in the first line of your for loop. It is a string that is a name of a property of the obj object. In the first iteration of the loop, propt would be "name".
Objects in JavaScript are collections of properties and can therefore be looped in a for each statement.
You should think of obj as an key value collection.
If running Node I'd recommend:
Object.keys(obj).forEach((key, index) => {
console.log(key);
});
While the top-rated answer is correct, here is an alternate use case i.e if you are iterating over an object and want to create an array in the end. Use .map instead of forEach
const newObj = Object.keys(obj).map(el => {
//ell will hold keys
// Getting the value of the keys should be as simple as obj[el]
})
I want to add to the answers above, because you might have different intentions from Javascript. A JSON object and a Javascript object are different things, and you might want to iterate through the properties of a JSON object using the solutions proposed above, and then be surprised.
Suppose that you have a JSON object like:
var example = {
"prop1": "value1",
"prop2": [ "value2_0", "value2_1"],
"prop3": {
"prop3_1": "value3_1"
}
}
The wrong way to iterate through its 'properties':
function recursivelyIterateProperties(jsonObject) {
for (var prop in Object.keys(example)) {
console.log(prop);
recursivelyIterateProperties(jsonObject[prop]);
}
}
You might be surprised of seeing the console logging 0, 1, etc. when iterating through the properties of prop1 and prop2 and of prop3_1. Those objects are sequences, and the indexes of a sequence are properties of that object in Javascript.
A better way to recursively iterate through a JSON object properties would be to first check if that object is a sequence or not:
function recursivelyIterateProperties(jsonObject) {
for (var prop in Object.keys(example)) {
console.log(prop);
if (!(typeof(jsonObject[prop]) === 'string')
&& !(jsonObject[prop] instanceof Array)) {
recursivelyIterateProperties(jsonObject[prop]);
}
}
}
What for..in loop does is that it creates a new variable (var someVariable) and then stores each property of the given object in this new variable(someVariable) one by one. Therefore if you use block {}, you can iterate. Consider the following example.
var obj = {
name:'raman',
hobby:'coding',
planet:'earth'
};
for(var someVariable in obj) {
//do nothing..
}
console.log(someVariable); // outputs planet
Here I am iterating each node and creating meaningful node names. If you notice, instanceOf Array and instanceOf Object pretty much does the same thing (in my application, i am giving different logic though)
function iterate(obj,parent_node) {
parent_node = parent_node || '';
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
var node = parent_node + "/" + property;
if(obj[property] instanceof Array) {
//console.log('array: ' + node + ":" + obj[property]);
iterate(obj[property],node)
} else if(obj[property] instanceof Object){
//console.log('Object: ' + node + ":" + obj[property]);
iterate(obj[property],node)
}
else {
console.log(node + ":" + obj[property]);
}
}
}
}
note - I am inspired by Ondrej Svejdar's answer. But this solution has better performance and less ambiguous
Also adding the recursive way:
function iterate(obj) {
// watch for objects we've already iterated so we won't end in endless cycle
// for cases like var foo = {}; foo.bar = foo; iterate(foo);
var walked = [];
var stack = [{obj: obj, stack: ''}];
while(stack.length > 0)
{
var item = stack.pop();
var obj = item.obj;
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
// check if we haven't iterated through the reference yet
var alreadyFound = false;
for(var i = 0; i < walked.length; i++)
{
if (walked[i] === obj[property])
{
alreadyFound = true;
break;
}
}
// new object reference
if (!alreadyFound)
{
walked.push(obj[property]);
stack.push({obj: obj[property], stack: item.stack + '.' + property});
}
}
else
{
console.log(item.stack + '.' + property + "=" + obj[property]);
}
}
}
}
}
Usage:
iterate({ foo: "foo", bar: { foo: "foo"} });
You basically want to loop through each property in the object.
JSFiddle
var Dictionary = {
If: {
you: {
can: '',
make: ''
},
sense: ''
},
of: {
the: {
sentence: {
it: '',
worked: ''
}
}
}
};
function Iterate(obj) {
for (prop in obj) {
if (obj.hasOwnProperty(prop) && isNaN(prop)) {
console.log(prop + ': ' + obj[prop]);
Iterate(obj[prop]);
}
}
}
Iterate(Dictionary);
To further refine the accepted answer it's worth noting that if you instantiate the object with a var object = Object.create(null) then object.hasOwnProperty(property) will trigger a TypeError. So to be on the safe side, you'd need to call it from the prototype like this:
for (var property in object) {
if (Object.prototype.hasOwnProperty.call(object, property)) {
// do stuff
}
}
Check type
You can check how propt represent object propertis by
typeof propt
to discover that it's just a string (name of property). It come up with every property in the object due the way of how for-in js "build-in" loop works.
var obj = {
name: "Simon",
age: "20",
clothing: {
style: "simple",
hipster: false
}
}
for(var propt in obj){
console.log(typeof propt, propt + ': ' + obj[propt]);
}
If you just want to iterate to map property values then lodash has _.mapValues
const obj = {
a: 2,
b: 3
}
const res = _.mapValues(obj, v => v * 2)
console.log(res)
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.21/lodash.min.js"></script>

Create javascript object with string type key

I want to create an object some thing like this
var key = "key";
var obj={};
obj[key] = "value";
My required output is
{ "key":"valie"}
Key type must be string because i have keys like #12:5 , #12:89 ( orientDB ids ).
REASON:-
Because embeddedList of orientDB is not accepting any key without quotes.
Thanks
You're probably looking for JSON syntax.
Here's output from my console.
var key = "key"; //var not Var
var obj={}; //same here
obj[key] = "value";
"value"
obj
Object {key: "value"} //key is not in quotes, need to stringify!
JSON.stringify(obj);
"{"key":"value"}"
Object literals in javascript can be declared with quoted keys:
{
"Okeli-dokeli": "Flanders",
"Doh!": "Simpson!"
}
You can also dynamically assign values to a key in javascript with the bracket syntax:
var x = {};
x["A B C"] = "foo";
ADDED:
The JSON format is based on a subset of javascript but has object keys which are always quoted. Therefore converting any javascript object to JSON will "stringify" the keys:
> JSON.stringify( { a : 'b' } )
> "{"a":"b"}"
In the off chance you are not expecting nested objects, this can easily work as well:
var key = "key";
var obj={};
obj[key] = "value";
var s = "{\r\n";
for (var p in obj) s+= ' "'+p+'": "' + obj[p] + '"\r\n';
s += "}\r\n";
Also, it's var, not Var (no capital first letter).

iterate object key value as an array

I'm trying to understand to iterate an array like object:
var obj = {0:'a',1:'b'}
function logArgs(){
Array.prototype.forEach.call(arguments,function(elem,idx){
console.log(idx + '. ' + elem);
})
}
//now calling this fails:
logArgs(obj)
//logs
0. [object object]
But I wanted a result like this:
0. a
1. b
It isn't an array-like object because it misses one key feature. A length property.
To iterate over an object, you can use this code:
for (var key in obj) {
// Protect against inherited properties.
if (obj.hasOwnProperty(key)) {
console.log(key, obj[key]);
}
}
In ES5, you can do:
Object.keys(obj).forEach(
function(key) {
var val = obj[key];
console.log([key, val]);
}
);
Important notes
NEITHER of this is guaranteed to return the values in array order. It may return [1, 0].
As #jfriend00 mentioned, the property names are strings. (This is also true of arrays, but arrays tend to hide that fact from you.)
To iterate over the keys of each object parameter passed to your function, you'd want something like this:
function logArgs(){
Array.prototype.forEach.call(arguments,function(elem,idx){
console.log("argument " + idx);
Object.keys(elem).forEach(function(key) {
console.log(" key " + key + ": " + elem[key]);
});
})
}
With your sample object, that'd log
argument 0
key 0: a
key 1: b
Note that the order of iteration through object property names, either with for ... in or with Object.keys(), is not defined in JavaScript. A runtime environment is free to hand over the keys in a literally random order any time you ask for them. They don't, of course, but writing code to depend on that is a bad idea.
I would do it in a different way using Object.keys()
Please refer the fiddle
var obj = {0:'a',1:'b'}
var keys = Object.keys(obj);
keys.forEach(function(key){
console.log(key + '. ' + obj[key]);
});
Using the same logic in OP's function.
var obj = {0:'a',1:'b'}
function logArgs(obj){
var keys = Object.keys(obj);
keys.forEach(function(key){
console.log(key + '. ' + obj[key]);
});
}
logArgs(obj)
Logs:
0. a
1. b
The usual iteration of properties of an object is like this:
var obj = {'0':'a', '1':'b'};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
// property name is in prop
// value is in obj[prop]
console.log(prop + ": " + obj[prop]);
}
}
Working demo: http://jsfiddle.net/jfriend00/45jwx6zg/
Keep in mind that (per the spec of the language) the properties of an object are not in any guaranteed order and all property names are string values.
You can't directly iterate an object (even one with 0, 1, 2 ... n as properties) like an array because it doesn't have a .length property. You could (although I don't know why this would be useful), extract the properties of the object into an array using Object.keys() and then use that for your iteration, but I'm unclear why any of that would be useful and not just much more complicated code than is required.
var obj = {'0':'a', '1':'b'};
Object.keys(obj).forEach(function(prop) {
console.log(prop + ": " + obj[prop]);
});
Unless you wanted to provide a custom sort to the keys, I can't see any reason to do it this way. Object.keys() also requires IE9 or higher.

How can I get all entities with a certain name from a JSON Array

I got some json that has objects nested within objects. I need to extract every entity that has the name "body". is there a way to do this without writing a long algorithm?
http://www.reddit.com/r/AskReddit/comments/22rx5c.json
You need to recursively loop through each node and its children and check their key name. There are libraries that can help you with this. Alternatively you could use xpath for JSON.
You can try so:
$.getJSON('http://www.reddit.com/r/AskReddit/comments/22rx5c.json', function(json){
result = [];
recurse('body', json);
console.log(result);
});
function recurse(toFind, json){
for( var key in json ){
if( typeof json[key] == 'object' ){
recurse( toFind, json[key] );
}
if( key == toFind ){
result[result.length] = json[key];
}
}
};
here you can find the JSFiddle

Finding value in json string

Below is what I have as JSON String.
{
"ID_A0001":{"areaID":"A0001","shopID":"SH004","quantity":14},
"ROW_INFO":{"areaID":"VARCHAR","shopID":"VARCHAR","quantity":"INT"},
"ID_A0002":{"areaID":"A0002","shopID":"SH008","quantity":18}
}
What I want is to get the JSONObject which have ID as ID_A i.e. ID_A0001 & ID_A0002.
I was thinking of using jsonObject.getString("ID_A"), but that is not possible. Could someone tell me what should I do so that I will get as below output.
{
"ID_A0001":{"areaID":"A0001","shopID":"SH004","quantity":14},
"ID_A0002":{"areaID":"A0002","shopID":"SH008","quantity":18}
}
The following code does what you want, assuming the object you posted is stored in obj. In case you actually have a JSON string instead of an object, use JSON.parse() to convert the string to a JavaScript object.
var obj2 = {};
for(var key in obj) {
if(key.substr(0, 4) == 'ID_A') {
obj2[key] = obj[key];
}
}
In the json object you have mentioned, you can modifiy it as follows.
var jsontest={
ID_A0001:{"areaID":"A0001","shopID":"SH004","quantity":14},
ROW_INFO:{"areaID":"VARCHAR","shopID":"VARCHAR","quantity":"INT"},
ID_A0002:{"areaID":"A0002","shopID":"SH008","quantity":18}
};
for(var key in jsontest) {
if(key.substring(0,4)=='ID_A')
alert('key: ' + key + '\n' + 'value: ' + jsontest[key].areaID);
}
http://jsfiddle.net/FBLvP/
Here is a useful link which shows us how to get the list of keys from a json object
http://encosia.com/using-jquery-1-6-to-find-an-array-of-an-objects-keys/1

Categories