Parsing JSON in JavaScript using a variable [duplicate] - javascript

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]);
});

Related

Cannot access a JSON attribute in a converted array [duplicate]

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)

Accessing a JSON key based on a lower level property in Javascript [duplicate]

This question already has answers here:
How to find object in array by property in javascript?
(3 answers)
Closed 5 years ago.
I'm pretty sure this has been asked before, but I can't seem to find the solution, for lacking the appropriate words to describe the issue.
I'm trying to access an object's key (e.g. "ID1"), in an object of objects, according to the value of one of its lower keys (e.g. "name":"name1").
The JSON object contains different ID objects, each of which contains a name and other properties.
mydata = {
"ID1": {"name":"name1","akey":true,"anotherkey":"foor"},
"ID2": {"name":"name2","akey":true,"anotherkey":"bar"},
"ID3": {"name":"name3","akey":false,"anotherkey":"foo"}
}
It's pretty simple to get the name if I know the ID, e.g.:
myname = mydata["ID1"].name; //returns "name1"
But what I'm trying to do is get the ID of an object if I know its name, so in short, the reverse of the above line. Is there any simple solution for this (in pure Javascript or jQuery)? Note: I know the names are unique.
If I'm understanding you correctly, Object.keys() can help you. It would look something like this:
var mydata = {
"ID1": {"name":"name1","akey":true,"anotherkey":"foor"},
"ID2": {"name":"name2","akey":true,"anotherkey":"bar"},
"ID3": {"name":"name3","akey":false,"anotherkey":"foo"}
}
Object.keys(mydata).forEach(function(id) {
var obj = mydata[id];
if (obj.name === "name1") {
// I found an object based on the "name" property.
// the 'id' variable holds a reference to it.
}
});
var mydata = {
"ID1": {"name":"name1","akey":true,"anotherkey":"foor"},
"ID2": {"name":"name2","akey":true,"anotherkey":"bar"},
"ID3": {"name":"name3","akey":false,"anotherkey":"foo"}
}
var parentId = Object.keys(mydata).find(function(key){
return mydata[key].name === 'name2';
});
console.log(parentId);
The only way to do it, is to traverse over every property-value.
var result = null;
for(var key in mydata) {
if(mydata[key].name==='name1'){
result = key;
break;
}
}
console.log(result);

Access generated properties with unknown property names in array of objects [duplicate]

This question already has answers here:
How to get property value in js object when key is unknown
(3 answers)
Closed 3 years ago.
Using the following generated array example structure, how can I loop through and extract the property names and their associated values from each object?
[{"bg_2":"0.50"},{"bg_7":"0.10"},{"bg_12":"0.20"}]
The number of objects may change, and the property names will not be consistent.
You can use Object.keys()[0] to get the key, then use the key to get the value.
JSFiddle
var myData = [{"bg_2":"0.50"},{"bg_7":"0.10"},{"bg_12":"0.20"}];
for (var i = 0; i < myData.length; i++) {
var myObject = myData[i];
var firstKey = Object.keys(myObject)[0];
var value = myObject[firstKey];
console.log(firstKey + ": " + value);
}
See also: ECMAScript® Language Specification: 15.2.3.14 Object.keys ( O )
Expanding on #AR7's answer, in the case that there may be multiple properties in each of the objects you can cache the object returned by Object.keys() and loop through each property within the array loop.
Using the method below, you can handle any number of properties within the object.
I realize this may not be any more useful in this specific situation than the aforementioned answer, but hopefully it will be useful to future viewers.
JSFiddle
var a = [
{ "bg_2":"0.50", "bg_7":"0.10", "bg_12":"0.20"},
{ "bg_2":"0.50", "bg_7":"0.10"},
{ "bg_2":"0.50"}
];
a.forEach(function(o){
console.log(o);
var k = Object.keys(o);
for(var i in k)
console.log(k[i], ':', o[k[i]]);
});

how iterate through this json object (not with jquery) [duplicate]

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!!

Merge Javascript objects, can't seem to find correct way [duplicate]

This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 9 years ago.
Hi i've been struggling a bit and i cant seem to find why the methods i found dont work, could be "fixture-0"
First Object array
personformdata[i]: "{"isInvalid":false,"agentRole":"role"}"
Second
address_ids[i] : "[{"address_id": "fixture-0" }]"
preferable out come, something like this.
"{"isInvalid":false,"agentRole":"role", "address_id": "fixture-0"}"
you can do it like:
var mergedObj={};
for(var key in personformdata[i])
mergedObj[key]=personformdata[i][key];
for(var key in address_ids[i])
mergedObj[key]=address_ids[i][key];
or if you use jQuery:
var mergedObj={};
$.extend(mergedObj, personformdata[i], address_ids[i]);
I myself usually use vanilla JavaScript and prefer not using jQuery.
you can use :
var object = $.extend({}, object1, object2);
for xample you can visit this url.
http://api.jquery.com/jQuery.extend/
If you want to create a new array with merged objects, just do this with a for loop:
var newData = { };
for (var i = 0; i < personformdata.length; i++)
{
newData[i] = {
isInvalid : personformdata[i].isInvalid,
agentRole : personformdata[i].agentRole,
address_id : address_ids[i].address_id
};
}

Categories