for in and objects inside objects - javascript

I have a json response from an API which returns an object that contains objects
something like:
{Object}->{results}->{manyObjects}
when running this:
var list = data.results.list;
for(val in list){
console.debug(typeof val);
}
the console returns strings instead of Object.
Could someone help me scan the objects?

In your code val is just the key inside the object, not the value that key points to. Try this instead:
for(var val in list) {
console.debug(typeof list[val]);
}
Though with that in mind you may want to rename val to something else.

The for in loop will return all of the property names of the list object. You must reference these properties on the object to receive a handle to them.
var list = data.results.list;
for(val in list){
console.debug(typeof list[val]);
}

Related

How i can store data use this pattern - Object inside object inside object or object inside object inside array

Please give me answer use JavaScript code. How i can store data like this
let obj = new Object;
obj.prop = 5; // Good
// but when i put third value like obj.prop.newObjectInside= 5 /Return error/
// How i can do it? or for example
obj.prop.array = 5 // Return error
I need add third object or array inside and use this pattern in my loop.
Thank you and if you know some articles or reference please write me too.
Try
obj.prop = { array : 5 }
or since it seems like you desire it to be an array you can do
obj.prop = { array : [5] }
You should then be able to do array ops like so
obj.prop.array.push(value);
Note the key here is to ensure that the second child is initialized, so you have to at least have an empty array
obj.prop = { array : [] }

Converting object to array

I'm getting list of elements but it is object when I want it to be array. I got simply code like this:
var obj = document.getElementsByClassName('_54nc');
var arr = $.map(obj, function(value, index) { return [value]; });
console.log(typeof arr);
And console is saying "object". How do I convert this?
In javascript, typeof an array is object. One way you can check if you are getting an array is to look at the constructor of the object:
possibleArray.constructor == Array
If this condition returns true then you have yourself an array.
It is also worth mentioning that you have mixed plain javascript with jQuery. You could improve your code by simply having the following:
var arr = $('._54nc')
You can then use arr[0] to get the first element or arr[1] to get the second and so on.
arr will be an array like object, which in javascript, support numeric subscripting.

How to iterate over an Array of objects with Ext.iterate (or JS)?

I know there is plenty of answers for this question on the net, but still I can't make it work.
After a callback on a JSON POST, I'm retrieving an Array of Object.
On the console log of the browser, the array is like this :
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
where inside each object, there is stuff like :
id4blob: "1084"
so I assume the array could be like this (correct me if I'm wrong):
[{id4blob: "1084"},{id4blob: "2008"}, [...]]
The array is stored in a variable called stationsParse
I want to iterate over these values, I've found
Ext.iterate
So I did this :
Ext.iterate(stationsParse, function(key, value) {
console.log(key + value);
});
and then tried this (which seems yo be the same but in pure JS)
for (key in stationsParse) {
var value = stationsParse[key];
console.log(key + value);
}
But none is working, nothing is displayed in my console.
Still, the function is well triggered, I can see it into Chrome console, but the for is ignored.
What Am I doing wrong ?
Is this the correct way to iterate over an array of objects ?
Try something like this:
var stationsParse = [{id: 1, someproperty: 2}, {id: 2, someproperty: 101}];
Ext.each(stationsParse, function(ob){
Ext.Object.each(ob, function(property, value){
console.log(property, value);
});
});
Here I am using Ext.each to iterate over each element in the stationsParse array. Each element in that array is an object. To iterate over each property in the object I use Ext.Object.each. Both 'each' functions take the variable you want to iterate over as its first parameter and a function as its second parameter. The function will be run on each element of the array/property of the object.
If you want to use vanilla JS to loop over an array, a simple for loop will do the the trick. Access the value of each object's id4blob property using dot notation.
for (var i = 0, l = arr.length; i < l; i++) {
console.log(arr[i].id4blob)
}
The for...in loop is generally reserved for looping over an object's properties.
Demo
I was able to make this work:
for (var i in family) {
console.log( family[i]["name"] );
}
in this tutorial on Codecademy, where family is an array of objects.
The only difference I can see is the var in front of my iterator variable i.

Construct object name, then pass object to function?

I'm working on existing Javascript code, which uses datasets stored in objects which are named data1, data2, etc. The numbers are IDs taken from a database.
Now, I need to write a little additional function which takes the IDs as input, then constructs the appropriate object name using that Id, and then passes that object to a function as a parameter.
So, something like:
function doStuff(id){
var objname="data"+id;
//now, I need to pass the object (not just the name) to a function
someFunction(objname); //this obviously doesn't work, because it just passes the object name as a string
}
So, how do I pass the actual object to the function, given that I have the object name?
The question sounds elementary, and I assume there's a method which does just this, but google doesn't seem to help.
Since the objects exist, you need a way to "find" them. I suggest you create a relationship between the string and the object using a key-value array - the key is the string, and the value is the object. You can then index the array with the string, and it will return the object.
Create an object and store in it keys like so:
var obj = {
data0 : "example 1",
data1 : "example 2"
}
Then you can access the properties like so:
function doStuff(id) {
var key = "data" + id;
someFunction(key);
}
someFunction(key) {
return obj[key];
}

How to extract a json object that's inside a json object

Convert this:
{"items":[{"id":"BLE89-A0-123-384","weight":"100","quantity":3},
...
{"id":"BLE10-A0-123-321","weight":"100","quantity":4}],
"country":"JUS",
"region":"A",
...
"timeout":"FILLER"}
To this:
{"BLE89-A0-123-384": "3", "BLE10-A0-123-321": "4"} that is... {id: quantity}
I found an answer that almost does what I need: Searching for an Object inside the JSON. But that answer doesn't help me because it's only at the first level (one json object). My problem is at the second level (json object within a json object). Thanks in advance!
It helps if you don't think of JSON objects as JSON objects. Once you run a JSON string through JSON.parse, it is a native JavaScript object.
In JavaScript, there are two ways to access objects.
Dot Notation
The dot notation goes like this
myObject.name
See the dot? You can use that to access any object property (which indeed may be another object in javascript, as long as it has a valid dot notation name). You can't use characters like -, ., and the space character.
Bracket Notation (may be another name)
myObject["variableName"]
Like dot notation but allows some other characters, like - and the space character.. Does exactly the same thing.
Using these notations is useful because we can access nested properties.
myObj.foo.bar.baz()
Now let's get to your JSON object...
{"items":[{"id":"BLE89-A0-123-384","weight":"100","quantity":3,"stock":0},
{"id":"BLE10-A0-123-321","weight":"100","quantity":4,"stock":0}],
You might want to brush up on the JSON format yourself, but in your example, here's a few clues...
{ Means the start of an object. (Keep in mind your entire JSON string is an object itself.)
} Means the end of an object.
"variable" (with quotes! important in JSON, but not when accessing/declaring javascript objects) assigns a property to your object.
: Is the assignment operator in both JSON and JavaScript objects.
Anything to the right of the : is the value you are assigning to the property on the left.
, Means you are starting a new property within an object.
You probably know that [] with , commas inside means an array.
When we run your string through JSON.parse(string), we'll get an object that looks like this...
var myResponse = JSON.parse(response);
You can now use it as a native JavaScript object. What you're looking for is a nested property within "items".
var items = myResponse.items; //alternatively you could just use myResponse.items
Since items is an array of objects, we'll need to iterate through it in order to convert the existing object into a new object.
var i;
var result = {} ; //declare a new object.
for (i = 0; i < items.length; i++) {
var objectInResponse = items[i]; //get current object
var id = objectInResponse.id; //extract the id.
var quantity = objectInResponse.quantity;
result[id] = quantity; //use bracket notation to assign "BLE89-A0-123-384"
//instead of id. Bracket notation allows you to use the value
// of a variable for the property name.
Result is now an object that looks like:
{
"BLE89-A0-123-384" : 3, //additional properties designated by comma
"BLE10-A0-123-321" : 4 // The last key/value in an object literal CANNOT
// have a comma after it!
}
You can access the properties using bracket notation.
var BLE89 = result["BLE10-A0-123-321"]; //use quotes, otherwise JavaScript will try to look up the value of a variable.
You can try with:
var obj = {
"items":[
{"id":"BLE89-A0-123-384","weight":"100","quantity":3},
{"id":"BLE10-A0-123-321","weight":"100","quantity":4}
],
"country":"JUS",
"region":"A",
"timeout":"FILLER"
};
var quantities = {};
obj.items.forEach(function (item) {
quantities[item.id] = item.quantity;
});
quantities will then be the object {"BLE89-A0-123-384":3,"BLE10-A0-123-321":4}. forEach is a native method of array objects in JavaScript that lets you iterate through their elements. You may want to put that piece of code inside a function:
function getQuantities(obj) {
var quantities = {};
obj.items.forEach(function (item) {
quantities[item.id] = item.quantity;
});
return quantities;
}
You need to do the following:
var newJSON = {};
for (var i = 0; i < oldJSON.items.length; i++) {
newJSON[oldJSON.items[i].id] = oldJSON.items[i].quantity;
}

Categories

Resources