This question already has answers here:
How do I iterate over a JSON structure? [duplicate]
(13 answers)
Closed 8 years ago.
I would like to iterate through a json object which I got from var jsonObj json_encode( <?php echo $php_array ?>);. This looks to me like a different format to what most people have. For example, w3schools shows this as a json object:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
Mine seems to have completely structure:
{"PINEFOREST JEWELRY":
["3034.25","2002-01-02"],
"AMBERS DESIGN":
["2034.75","2002-01-02"],
"ELEGANT JEWELERS":
["206","2002-01-02"],
"SALEM'S JEWELERS":
["406","2002-01-02"]}
Am I able to iterate through this?
You can use a for loop to iterate through the object's direct properties as follows:
var val;
for(var key in obj) {
if(obj.hasOwnProperty(key)){
val = obj[key];
console.log(val);
}
}
You can use a for in with a nested for
for (var key in data) {
for (var i = 0; i < data[key].length; i++) {
console.log(data[key][i]);
}
}
Yes you can itterate through it as it is valid json.
To start of you need to convert the json into something javascript can itterate over, which you can do with JSON.parse() (MDN). Im assuming that the 'json' you described above is a string of 'json' so:
var jewellery = JSON.parse(myJson); // replace myJson with whatever variable is holding your json
At this point you have an object which you can itterate over. One of the easiest ways to do this would be by using Object.keys() (MDN) and Array.forEach() (MDN) like so:
Object.keys(jewellery).forEach(function (key) {
console.log(key); // would log 'PINEFOREST JEWELRY' the first time
jewellery[key].forEach(function (price) {
console.log(price); // Should log '3034.25' the first time
}
});
Give that a try, otherwise you could still use the other solutions other people have submitted, either or would work. This is how I would do it though!!
Related
This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Closed 2 months ago.
I would like to understand what am I doing wrong here. The problem is simple: I get an array in a response and I would need to access to its elements by name. Therefore I use Map to create a pair of Metric and Value. Subsequently, I use JSON stringify which I thought would be enough.
But when I try to access the element (array.Speed), I am getting Undefined.
var response=[
{
metric: "Speed",
value: "145",
},
{
metric: "Deceleration",
value: "76.5",
}
];
let array=[];
response.map(m=> {
array.push({
[m.metric]:m.value
});
});
var j=JSON.stringify(array);
console.log(j.Speed); //UNDEFINED
var js=JSON.parse(j);
console.log(js.Speed); //UNDEFINED
Stringify and access, converting to JSON later even, as described.
array is : [ { Speed: '145' }, { Deceleration: '76.5' } ] You can access speed like this: js[0].Speed .
The fact that j.Speed is undefined is to be expected since j is a string (and not an array neither an object)
I'm converting an xml string to json using php and then posting it to a
javascript file where I try to iterate it. When the object contains more than one object, json contains an array of objects like the first sample and I can iterate using the .length function but when the object contains only 1 object an array is not being created and the .length function fails. How can I make the iteration work in both cases without knowing the object's name?
Sample 1:
{"class":[
{
"name":"history",
"grade":"10"
},
{
"name":"chemistry",
"grade":"8"
}
]
}
Sample 2:
{"class":
{
"name":"history",
"grade":"10"
}
}
You could check length, and if it's undefined it means it's just an object, then you make it an array with just one element:
if collection.length == undefined:
collection = [collection]
# the rest of the code doesn't need to be changed
You can use for for that and you don't need length
var test = {"class":[
{
"name":"history",
"grade":"10"
},
{
"name":"chemistry",
"grade":"8"
}
]
}
for (var i in test){
console.log(test[i]);
}
You can check to see if the object is an array first: Array.isArray(obj) . If it isn't then you know you don't need to iterate it.
var obj = {"class":[
{
"name":"history",
"grade":"10"
},
{
"name":"chemistry",
"grade":"8"
}
]
}
if (!Array.isArray(obj)) return obj;
// else iterate it.
You have to know the data type of the variable before knowing how to use .length properly.
var dataTypeLength;
var data = {
"class":
{
"name":"history",
"grade":"10"
}
}
if (Array.isArray(data.class)) {
dataTypeLength = data.class.length;
} else {
dataTypeLength = Object.keys(data.class).length;
}
console.log(dataTypeLength);
This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 6 years ago.
Was looking online for some help on this but couldn't find quite what I was looking for. I know how to parse a JavaScript variable, however, let's say I have the following JSON
{
"CPU INFO": {
"cpu0": "val",
"cpu1": "someval"
}
}
Let's assume I don't know how many CPUs there are and I want to set keys of a dictionary to the values. For example, if I had a loop such as:
for(var counterCPUS = 0; counterCPUS < numCPUs; counterCPUS++)
{
var currCPU = "cpu"+counterCPUS;
dictionary["cpu"+counterCPUS] = furtherCPUObject.currCPU;
}
Obviously this would not work since it would look for a String "currCPU", not "cpu0". How can I do what I am trying to achieve, assuming it is possible.
Thanks!
You can iterate objects using for..in, or you can get the object's keys as an array by using Object.keys and iterate over that:
var json = {
"CPU INFO": {
"cpu0": "val",
"cpu1": "someval"
}
};
for (var cpuKey in json['CPU INFO']) {
console.log(cpuKey, '=>', json['CPU INFO'][cpuKey]);
}
Object.keys(json['CPU INFO']).forEach(function(key) {
console.log(key, '=>', json['CPU INFO'][key]);
});
I know this questions exists like 100 times, but I just can't transfer the solutions to my code, so I hope you can help me. This should be pretty easy but I just don't get it working.
This is just my code with other variable because of reasons:
My Code:
for (var key in array) {
}
The JSON I want:
[{
key: "One",
y: 5
}, {
key: "Two",
y: 2
},];
Pseudo JSON:
[{
key: key,
y: array[key].data
},{
key: key,
y: array[key].data;
},];
You can try this solution:
var data = [];
for (var key in array) {
data.push({
key : key,
y : array[key].data
});
}
console.log(data);
But, what about Pseudo JSON:?
DEMO - See console (chrome) for output
I don't understand what is 'array'. Is it an object or an array?
I think what you want might be this, if 'array' is an array:
var new_arr = [];
your_array.forEach( function(entry) {
new_arr.push({key: entry, y: entry.data}); // you should change it according to your need.
})
return JSON.stringify(new_arr);
Or if 'array' is just an object, you may need this:
var new_arr = [];
for (key in array) {
new_arr.push({key: key, y: array[key].data}); // you should change it according to your need.
}
return JSON.stringify(new_arr);
JSON is just a syntax for expressing objects and arrays independently of a scripting language's syntax.
Apparently you want to convert your array into another structure and have this expressed in JSON. The conversion to JSON is usually performed by the built-in function JSON.stringify.
Assuming your array isn't really an array (which has only numeric indices, usually without gaps), but more an object-like structure, I'd suggest the following code:
var data = []
for (var key in array)
{
data.push({key: key, y: array[key].data});
}
var json = JSON.stringify(data);
//...
If array really was an array you shouldn't use a for-in-loop. Otherwise you should consider renaming it to avoid confusion.
you can use following line to create an array of json
var jsonArr = [];
then you can create json object from following line
var obj = new Object();
put data in json object as following
obj['id'] = 123;
obj['name'] = 'ABC';
then put json object in json array as
jsonArr.push(obj);
you want to add multiple objects in json array then simply create json object and add one by one using push method.
[{"id":"123","name":"ABC"}]
it's frustrating that we can't select JSON elements (or really any elements) using a similar code like this:
//An JSON object is parsed into Response beforehand
for(var count = 1; count <= Response.objCount; count ++) {
console.log(Response.obj+count.content);
}
In the code, I want to output a JSON object like this:
{ "objCount" : 2 ,
"obj1" : { "result" : true ,
"content" : "blah blah 1" } ,
"obj2" : { "result" : true ,
"content" : "blah blah 2" } }
But no, we can't use variable as whole or part of an identifier in Javascript..
So, any suggestions on how to handle such JSON objects when I want to output each and every object?
Thank you!
If "Response" is your structure, then you can indeed do what you ask:
for(var key in Response) {
console.log(Response[key].content);
}
You can't loop on "length" because "Response" is not an array, and plain objects don't have a "length" property.
Now, one problem is that you can't be sure that you'll get the components out in any particular order. That is, the loop above may give you "obj2" before you get "obj1". You could address that problem in a couple of ways. First, you could re-think your data structure and store it as an array. Alternatively, you could fetch the keys and sort them, and then iterate through the sorted array of property names.
var keys = Object.keys(Response);
keys.sort(function(key1, key2) {
// comparison ...
});
for (var count = 0; count < keys.length; ++count)
console.log(Response[keys[count]].content);
The Object.keys() function only works in newer browsers, but you can do a similar trick with a for ... in loop to pull out the property names.
edit — with your updated structure that includes an explicit property of your own for the length, you can use a plain for loop:
for (var count = 1; count <= Response.objCount; ++count)
console.log(Response["obj" + count].content);
Use brackets to access the property using the property name as a string:
Response["obj" + count].content