difference between 2 objects/arrays - javascript

i have 2 objects, which are associated arrays from PHP in JSON. They have an structure like that´:
[object]
["green"]
['value1']=integer
['value1']=array...
["blue"]
['value1']=integer
['value1']=array...
[...]
The 1st Version of this object is loaded from webserver periodically using JSON.
By receiving this new JSON string from webserver, the current object moved to the variable "oldObj" while the new data stored into the variable "newObj".
It could be possible, that the new object will have less elements than the old object, like this:
[newObj]
["green"]
['value1']=integer
['value1']=array...
As you can see: "blue" is missing.
Now i need this elements which are part of the old Object / that means: which are missing at the new object (at this example: element "blue")
I tried the following, but without any success:
[...]
var newObj=data;
$.each (oldObj,function(i,n)
{if (newObj.i.length<1) {alert('missing: '+i);}
}
);//end foreach
Error message: "newObj.i is undefined"

According to your description, I think newObj or oldObj can be wrote as:
var newObj = {
"green": [
integer,
[array]
],
"blue": [
integer,
[array]
]
};
Is it right?
You could use :
for(p in Obj){
if(Obj.hasOwnProperty(p)){
// do something with p
}
}
to loop through the Obj's properties.

Related

javascript access multidimensional object not working

I have an object:
var Obj = [{
id: "",
position: {
cartesian: [],
polar: [],
bob: "INERTIAL"
}
}];
When I go to set obt.id
Obj.id="sam/reconnaissance - "+samName;
It works fine.
However when I go to access Obj.position.cartesian
(Obj.position.cartesian).push(fooBar[i][t][p]);
I get this error:
(Obj.position.cartesian).push(fooBar[i][t][p]);
^
TypeError: Cannot read property 'cartesian' of undefined
Why? I have tried Obj['position']['cartesian'] and still nothing
What am I doing wrong?
Obj is not an object, it is an Array so you have to access first element with index 0. Try it like
Obj[0]['position']['cartesian']
You aren't using an object, you are using an array.
An object looks like this:
var obj = {
id: 0
};
What you have is an object within an array: (note [)
var obj = [{id: 0}];
Obj is an array with single element as object, hence to access position you can use any of these syntax
Obj[0]['position']['cartesian']
Obj[0].position.cartesian
Again cartesian is an array hence to call push you can use
Obj[0]['position']['cartesian'].push(foobar[i][t][p])
Obj[0].position.cartesian.push(foobar[i][t][p])

Converting JSON to array key - value in javascript

I've been developing a web application where I'm receiving data in this format, from a node server:
"{""elements":[{"10sr2b2":{"total":0,"bad":22,"clients":["fc8e7f","fc8e7e"],"zone":"101900"}}]}"
The poblem is this data is an array key-value called "elements" where "10sr2b2" is the key of the first element of the array.
So when I call $.parseJSON() method, this return an object like this:
elements: Array[1]
0: Object
10sr2b2: Object
zone: "101900"
clients: Array[2]
0: "fc8e7f"
1: "fc8e7e"
length: 2
__proto__: Array[0]
bad: 22
total: 0
Where "10sr2b2" it's supposed to be the key and it's an object and I need to get this value somehow.
Can you help me?
You could use Object.keys to get the object keys.
var keys = Object.keys(data.elements[0]);
Can you change the format from the node server? It needs to send something more like:
"{""elements":[{"key": "10sr2b2" "value": {"total":0,"bad":22,"clients":"fc8e7f","fc8e7e"],"zone":"101900"}}]}"
If you know you'll always only have one key for each item, you can use a for..in loop that immediately breaks, for example
var i, key, obj = $.parseJSON(/*...*/);
for (i = 0; i < obj.elements.length; ++i) { // loop over elements
for (key in obj.elements[i]) break; // get key
// now can access
obj.elements[i][key]; // Object
}

Split one JSON return into several objects

So, I've been looking at this for a couple hours and am out of ideas. My app is returning a single JSON object, and I need to parse the 4 data sets out of it and make 3 charts and a table. For the life of me I can't figure out how to "extract" each part. The JSON looks like:
{
"allele":{
"12426597":{
"??":4,
"CC":3,
"TT":4,
"CT":12
},
"878198":{
"??":4,
"AA":1,
"AC":15,
"CC":3
},
"6447271":{
"??":4,
"GG":14,
"AG":5
}
},
"haplo":{
"CT,AG,AC":3,
"TT,GG,AC":1,
"CC,GG,CC":1,
"TT,AG,CC":1,
"TT,GG,CC":1
},
"exercise":"p1"
}
I need to grab the data just for the three key's/IDs (12426597,878198, 6447271) and make one bar chart for each of those (requiring a data transformation <== see). Then I need to plug it into Highcharts...their API calling for an ordered arrays for the keys and values.
I thought about first making an array of the IDs:
var snpsObj = data.allele_frequency; // data returned from $.getJSON
var snpList = [];
for (prop in snpsObj) {
if (!snpsObj.hasOwnProperty(prop)) {
continue;
}
snpList.push(prop);
}
Which does get me the wanted array. And then accessing the "sub" keys like:
snpsObj.snpList[0];
...to return hopefully, something like:
{
"CC" : 23,
"CT" : 36,
"TT" : 12,
}
But that doesn't work at all. The most I could get was a return of something like:
allele_frequency : [object Object ]
I know there's something basic I'm just forgetting in my head-cold-fogged mind... Any suggestions?
Highcharts needs the keys and labels formatted in arrays, like:
categories: ['C', 'T']
data: [ 3, 9] // C=3, T=9
I think you want to access
snpsObj[ snpList[0] ]
by using bracket notation, snpsObj.snpList[0] would try to get the "snpList" property of your snpsObj object.
Btw, instead of your for-in-loop to create the array with property names, you might want to use Object.keys (even if you need to shim it to support old browsers).

how to create JavaScript object using a for loop?

i have an object sample data:
[Object, Object, Object]
0: Object
test_id: "1"
area: "high"
1: Object
test_id: "1"
area: "saw"
2: Object
test_id: "2"
area: "look"
i am trying to create a new object by grouping by test_id.
var obj = new Object();
$.each(data, function(k, v){
obj[v.test_id] += {area: v.area};
});
this doesn't seem to work, it returns only one object line...
i am trying to get something like:
1: {
{area: "high"}
{area: "saw"}
}
2: {
{area: "look""
}
any ideas? thanks
After your edit I notice something, you're trying to create a javascript object with a property with no name, this is not the format. In JSON (javascript object notation) each property must have a value, what you are trying to store better fits an array.
Instead, push it into an array
$.each(data, function(k, v){
obj[v.test_id].area.push(v.area);
});
just remember to create obj[v.test_id] first and to set its area property to [].
This results in:
1: {
area: ["high","saw"]
}
3: {
area: ["look"]
}
Also, if you're willing to consider using underscore it has very powerful (yet basic) collection methods, you might want to have a look at http://underscorejs.org/#groupBy

Is there a way to get number of elements from object?

Let me explain in detail. I have below an object with me -
{
"OBJECT1" : {
"NAME1" : "VALUE1",
"NAME2" : "VALUE2",
"NAME3" : "VALUE3"
},
"OBJECT2" : {
"NAME4" : "VALUE4",
"NAME5" : "VALUE5"
}
}
From this object, I want to get something like number of elements in OBJECT1 = 3 and number of elements in OBJECT2 = 2. If at all this is possible using javascript.
Basically what I am trying to do is, to loop through the name value pairs available in the object dynamically so that if someone adds another element to object, I don't have to change my code.
Also any alternative is also ruled out since I am allowed to only use object in my use-case.
Without converting your object you could iterate through the object counting properties like so:
function countObjectProperties(obj)
{
var count = 0;
for(var i in obj)
if(obj.hasOwnProperty(i))
count++;
return count;
}
Expanding on why you need to use hasOwnProperty as I said in the comment below you can run into an issue where a library or browser has added methods and properties to Objects, in order to avoid counting these we check for hasOwnProperty before counting it. More details at MSDN or at Mozilla Developer Center
For JSON string that represent an object (which is your case), you cannot use any length property. you need to loop through the object (see Kristoffer S Hansen's answer).
If it represented an array, you could get the length with:
var len = arr.length;
JQuery makes it simpler:
var len = $(JSON).length;
To answer your broader goal, as specified in your question:
For looping through the properties, you can use the for..in construct:
for (var item in myobject) {
// some browsers add more properties to every object, we don't want those
if (myobject.hasOwnProperty(item)) {
do_something(item);
}
}
Assuming that myobject is the object in your question, this will loop through it and call do_something(OBJECT1) and do_something(OBJECT2); you can use the same construct to loop through the child objects:
// loop through OBJECT1 and OBJECT2
for (var item in myobject) {
// some browsers add more properties to every object, we don't want those
if (myobject.hasOwnProperty(item)) {
// loop through the item's children
for (var pair in item) {
if (item.hasOwnProperty(pair)) {
// each of the name:value pairs will be passed to this
do_something_else(item,pair);
}
}
}
}

Categories

Resources