I have an associative array here -
var dataset = {
"person" : [
{"userLabels": ["Name","Role"]},
{"tagNames": ["lName","role"]},
{"tableClass": "width530"},
{"colWidths": ["50%","50%"]}
]
}
I tried accessing the 'userLabels' object using jQuery using various methods but I failed. I think I am doing something wrong with basics. I want the userLabels object to be accessed using jQuery and the result should be an array, so I can perform the jQuery.inArray() operation.
Firstly, here's how you can access dataset using the method you have.
var dataset =
{
"person" : [
{"userLabels": ["Name","Role"]},
{"tagNames": ["lName","role"]},
{"tableClass": "width530"},
{"colWidths": ["50%","50%"]}
]
};
alert(dataset['person'][0]['userLabels']); //style 1
alert(dataset.person[0]['userLabels']); //style 2
alert(dataset.person[0].userLabels); //style 3
//Also you can use variables in place of specifying the names as well i.e.
var propName ='userLabels';
alert(dataset.person[0][propName]);
//What follows is how to search if a value is in the array 'userLabels'
$.inArray('Name', dataset.person[0].userLabels);
I'd like to ask why you're doing this in a such an 'interesting way'. Why don't you just make them all objects?
That's what I would do if I were you because if you think about it, a person IS an object and it should be noted that arrays are basically objects in Javascript with a 'length' property, though I won't elaborate on it here (feel free to do some research though). I'm guessing it's because you don't know how to iterate over object properties. Of course if it makes more sense to you, go for it.
Note one of the differences between an array and an object is that object properties need to be defined; you'll notice that I gave 'Name' and 'Role' values of 'undefined' below.
In any case, here is what I would do:
var dataset =
{
"person" : {
"userLabels": {"Name" : undefined,"Role": undefined},
"tagNames": {"lName" : undefined,"role" : undefined},
"tableClass": "width530",
"colWidths": ["50%","50%"]
}
};
for (var i in dataset) { //iterate over all the objects in dataset
console.log(dataset[i]); //I prefer to use console.log() to write but it's only in firefox
alert(dataset[i]); // works in IE.
}
//By using an object all you need to do is:
dataset.person.userLabels.hasOwnProperty('Role'); //returns true or false
Anyways, hope this helps.
var basic = dataset.person[0].userLabels;
// | | |
// | | --- first element = target object
// | --- person property
// ---- main-object
var userLabels = dataset.person[0].userLabels;
if ($.inArray(yourVal, userLabels) !== -1) {
doStuff();
}
Related
I want to merge two object using JavaScript
First
{
"user" : " Hari",
"friend" : "Shiva",
"friendList": ["Hanks"," Tom"," Karma"," Hari"," Dinesh"]
}
second
{
"user" : "Hari",
"friend" : " Shiva",
"friendList" : ["Karma"," Tom"," Ram"," Bindu"," Shiva",
" Kishna"," Bikash"," Bakshi"," Dinesh"]
}
and form a single object:
expected output
{
"user" : "Hari"
"friend" : "Shiva",
"friendList":[
["Hanks"," Tom","Karma"," Hari"," Dinesh"],
["Karma"," Tom"," Ram"," Bindu"," Shiva"," Kishna"," Bikash"," Bakshi"," Dinesh"]
]
}
Is it possible? I am sorry if it is wrong question....but I need to solve in this way and I do not have much idea about JavaScript.
You can add from one array to anther like this
var a={
"user" : " Hari",
"friend" : "Shiva",
"friendList": ["Hanks"," Tom"," Karma"," Hari"," Dinesh"]
};
var b={
"user" : "Hari",
"friend" : " Shiva",
"friendList" : ["Karma"," Tom"," Ram"," Bindu"," Shiva",
" Kishna"," Bikash"," Bakshi"," Dinesh"]
};
b.friendList.concat(a.friendList);
you will get on b all the array of a+b...
you will not get this structure that you want. For my code you will get an array of strings from a and b, if you want this structure you need to change the result to be an object and not array.
also can see example from : link
The following code will merge the objects as described in your question:
var firstObject = {
"user" : " Hari",
"friend" : "Shiva",
"friendList": ["Hanks"," Tom"," Karma"," Hari"," Dinesh"]
};
var secondObject = {
"user" : "Hari",
"friend" : " Shiva",
"friendList" : ["Karma"," Tom"," Ram"," Bindu"," Shiva",
" Kishna"," Bikash"," Bakshi"," Dinesh"],
};
function mergeMyObjectsIntoNew(first,second,copyFriendListArrayReference){
//.trim() is needed in the compare here because example data has a leading space
// in secondObject.friend
if(first.user.trim() === second.user.trim()
&& first.friend.trim() === second.friend.trim()){
var newObject={}; //The new object
newObject.user = first.user;
newObject.friend = first.friend;
newObject.friendList = []; //Create new array
if(copyFriendListArrayReference){
//This copies references for the arrays in first.friendList and
// second.friendList into the array new.friendList. These will be the
// same arrays as exists in first and second. Changes to the contents
// of those arrays will affect the arrays in the newObject.
newObject.friendList[0] = first.friendList; //add friendList from first
newObject.friendList[1] = second.friendList; //add friendList from second
}else{
//This copies the string contents of the arrays in first.friendList and
// second.friendList into the array new.friendList. These will NOT be the
// same arrays as exists in first and second. Changes to the contents
// of those arrays will NOT affect the arrays in the newObject.
// This is the default behavior.
//Copy contents of friendList from first
newObject.friendList[0] = Array.from(first.friendList);
//Copy contents of friendList from second
newObject.friendList[1] = Array.from(second.friendList);
}
return newObject;
}//implicit else due to 'return' in all if paths
return null; //Indicate to caller that there was not a match.
}
//Get new merged object with copy of friendList
mergedObject = mergeMyObjectsIntoNew(firstObject,secondObject);
console.log(mergedObject);
Comments
Using multiple very similarly structured objects is, often, a bad idea
It is, generally, not a good idea to use objects that have two different structures, unless you are keeping those objects distinctly separate. When you do have multiple structures for objects which you treat similarly (i.e. you use the same functions/methods to manipulate objects with both structures), all of your code has to account for each of the multiple structures. This can rapidly make your code much more complex and, potentially, more confusing than it would need to be if you did not have multiple structures for objects which you treat similarly.
In this case, you are wanting your result object to have a friendList property which is an array of arrays of strings whereas your source objects have a friendList property which is an array of strings. If you are going to use mergeMyObjectsIntoNew on both object structures, having the two different structures for the friendList property would require more logic in mergeMyObjectsIntoNew, if you want it to be able to operate on both types of object with the results you would, probably, expect.
For instance, the following code will not produce the result that you are probably expecting:
mergedFirstSecondObject = mergeMyObjectsIntoNew(firstObject,secondObject);
mergedthirdFourthObject = mergeMyObjectsIntoNew(firstObject,secondObject);
mergedFourObjects = mergeMyObjectsIntoNew(mergedFirstSecondObject,mergedthirdFourthObject);
This will produce an object that has a friendList property that is an array of arrays of arrays of strings. The mergedFourObjects object is structured like:
{
"user" : " Hari",
"friend" : "Shiva",
"friendList": [
[
friendListArrayFromFirstObject,
friendListArrayFromSecondObject
],
[
friendListArrayFromThirdObject,
friendListArrayFromFourthObject
]
]
}
In your case, you are probably better off picking to always have the friendList property be only one or the other of an array of array of strings, or an array of strings. Having the friendList property such that it might be either structure will significantly complicate your code everywhere you use these objects.
Using a class would be the better approach to handling your objects
If you are going to be using your objects in a larger project, it is probably a better idea to use a class for the object. This would allow you to move things like comparing the objects and merging the objects into methods of the class (e.g. MyObject.prototype.compare(second) and MyObject.prototype.merge(second). However, that is a discussion well beyond the scope of your question. If you want more information, I suggest you search for information about using object classes in JavaScript.
Following on from this question, I would like to create a DRY way of creating Js variables for a D3 graph which represents daily sentiment analysis of UK newspapers.
Here is some example code from my script:
var guardian,independent; // many more here
var gLine,gChart; // many more here
var iLine,iChart; // many more here
I am storing the newspaper-specific variables in an object:
var allObjects = { guardian : {line : gLine,chart : gChart},
independent : {line : iLine,chart : iChart}}// and so on for each newspaper
I assign the variables using functions as follows:
function makeLine(name){return d3.svg.line().y(function(d) { return y(d[name]); }); }
// and so on for each newspaper attribute in AllObjects
Rather than repeating myself all the time, making each object individually:
makeLine('guardian'); makeLine('independent'); // etc
...which works fine, I would like to be able to iterate over all the newspapers, and assign the objects with a single function for all newspapers, something like:
var allFunctions = {line: makeLine(),chart: makeChart()};
function make(type){
var myFunc = allFunctions.type;
for(var prop in allObjects){prop.type = myFunc(type);}
}
So that make(line) would assign gLine, iLine, etc
The problem is that as the variables in allObjects.guardian are undefined, this method isn't working.
Any suggestions as how to refactor in this way?
Rather than repeating myself all the time, making each object individually:
makeLine('guardian'); makeLine('independent'); // etc
...which works fine, I would like to be able to iterate over all the newspapers, and assign the objects with a single function for all newspapers
If I'm reading that right, your "something like" is really close, see comments:
var allFunctions = {line: makeLine, chart: makeChart};
// Note no () here ----------------^ or here --------^
// We want the reference to the function, we don't want to call it (yet)
// Assuming `type` is "line", "chart", etc.
function make(type){
// Note brackets: We want the property whose name is in the type
// variable, not a property actually called "type"
var myFunc = allFunctions[type];
// ^----^------ We want the property whose name is in
// the `type` variable, not a property
// actually *called* "type"
for (var prop in allObjects) {
allObjects[prop][type] = myFunc(prop);
// ^----^-----^----------- Brackets again as above
}
}
How would I access ArrayObjectVariable inside
ArrayObject[0]? I know if you don't have a [ ] around it its as simple
as ArrayObject[0].ArrayObjectVariable?
var ArrayObjectVariableValue = 'AyOhVeeVee';
var ArrayObject = []
ArrayObject[0] = [{ ArrayObjectVariable : ArrayObjectVariableValue }];
alert(ArrayObject[0]???);
I didn't realize the whole "ArrayObject[0][0].ArrayObjectVariable" thing. Thanks for the replies. I was trying it with just one ("[0]") instead of two ("[0][0]"). My second question is, what is the second "[0]" for? I just tried making multiple variables and it still used "[0][0]" ? So what's the second "[0]" controlling?
Third question? I noticed that it created a variable outside the array when I did that? When I change the value of the variable in the array, it has no effect on the one outside of it? Likewise, when I change the value of the variable outside of the array it has no effect on the one inside it. Is there a way to create the array without creating a variable outside of the array with the same name? Thanks :)
OK figured it out :) Just make the Object in the array without the "[ ]". The whole point of this was to figure out how to access nested items but I got it now. Didn't realize how to make them without the "[ ]". Example for those of you struggling like I was:
// create variables that we are going to use in Array Objects. Or make a function with the values.
var ATV1 = 'AyTeeVeeOne', ATV2 = 'AyTeeVeeTwo', ANV1 = 'AyEnVeeOne';
var ATV3 = 'AyTeeVeeThree', ATV4 = 'AyTeeVeeFour', ANV2 = 'AyEnVeeTwo';
// Make an Array
var ArrayObject;
ArrayObject = [{}];
// Insert variables into Array object(s).
ArrayObject[0] = {ArrayTestObject1 : { ArrayTestValue1:ATV1,
ArrayNestedObject1:{ ArrayNestedValue1:ANV1 },
ArrayTestValue2:ATV2
}};
ArrayObject[1] = {ArrayTestObject2 : { ArrayTestValue3:ATV3,
ArrayNestedObject2:{ ArrayNestedValue2:ANV2 },
ArrayTestValue4:ATV4
}};
// Access Array Object Variables
alert(ArrayObject[0].ArrayTestObject1.ArrayTestValue1) // Example 1
alert(ArrayObject[1].ArrayTestObject2.ArrayNestedObject2.ArrayNestedValue2) // Example 2
ArrayObject[0][0].ArrayObjectVariable
You have an array for the value of ArrayObject[0], so treat it like any other array.
use this:here you have ArrayObject as array and you are creating index as zero to the array and in that on zeroth place ArrayObjectVariable key resides.
<script>
var ArrayObjectVariableValue = 'AyOhVeeVee';
var ArrayObject = []
ArrayObject[0] = [{
ArrayObjectVariable : ArrayObjectVariableValue }];
alert(ArrayObject[0][0].ArrayObjectVariable);
</script>
var profileDataCalls = [];
profileDataCalls['Profile'] = GetUserAttributesWithDataByGroup;
profileDataCalls['Address'] = GetUserAddresses;
profileDataCalls['Phone'] = GetUserPhoneNumbers;
profileDataCalls['Certs'] = GetUserCertifications;
profileDataCalls['Licenses'] = GetUserLicenses;
profileDataCalls['Notes'] = GetUserNotes;
My problem is the above JavaScript array is only a length of 0. I need an array that can be iterated over and holds the key(string) and value?
You want:
var profileDataCalls = {
'Profile' : GetUserAttributesWithDataByGroup,
'Address' : GetUserAddresses,
'Phone' : GetUserPhoneNumbers,
'Certs' : GetUserCertifications,
'Licenses' :GetUserLicenses,
'Notes' : GetUserNotes
};
Then you can access the values with, for example, profileDataCalls.profile or profileDataCalls[profile] (to retrieve whatever value is represented by the variable GetUserAttributesWithDataByGroup)
To iterate through the object, use:
for (var property in profileDataCalls) {
if (profileDataCalls.hasOwnProperty(property)) {
console.log(property + ': ' + profileDataCalls[property));
}
}
Javascript doesnt have associative arrays per say , what you are doing is adding properties to the Array instance. IE doint something like
profileDataCalls.Notes = GetUserNotes;
so you cant really use length to know how many properties your array would have.
now if your issue is iterating over your object properties , you dont need an array , just use an object :
profileDataCalls = {}
then use a for in loop to iterate over the keys :
for(var i in profileDataCalls ){
// i is a key as a string
if(profileDataCalls.hasOwnProperty(i)){
//do something with profileDataCalls[i] value , or i the key
}
}
it you have different requirements then explain it.
now the tricky part is profileDataCalls[0]="something" would be valid for an object({}), you would create a property only available through the lookup (obj[0]) syntax since it is not a valid variable name for javascript.
other "crazy stuffs" :
o={}
o[0xFFF]="foo"
// gives something like Object {4095:"foo"} in the console
Actually it also works like this:
var profileDataCalls = [{
Profile: GetUserAttributesWithDataByGroup(),
Address: GetUserAddresses(),
Phone: GetUserPhoneNumbers(),
Certs: GetUserCertifications(),
Licenses: GetUserLicenses(),
Notes: GetUserNotes()
}];
Then you can access the values with, for example, profileDataCalls[0].profile or profileDataCalls[0]["profile"].
To iterate through the object, you can use:
for (key in profileDataCalls[0]) {
console.log(profileDataCalls[0][key]);
}
Since this is an associative array, I never understood why people are saying its not possible in Javascript...in JS, everything is possible.
Even more, you could expand this array easily like this:
var profileDataCalls = [{
Profile: GetUserAttributesWithDataByGroup(),
Address: GetUserAddresses(),
Phone: GetUserPhoneNumbers(),
Certs: GetUserCertifications(),
Licenses:GetUserLicenses(),
Notes: GetUserNotes()
}{
Profile: GetUserAttributesWithDataByGroup(),
Address: GetUserAddresses(),
Phone: GetUserPhoneNumbers(),
Certs: GetUserCertifications(),
Licenses: GetUserLicenses(),
Notes: GetUserNotes()
}];
And access the array entries with profileDataCalls[0]["profile"] or profileDataCalls[1]["profile"] respectively.
What you want is an object:
Try
var profileDataCalls = new Object();
then reference your data as you do already.
I want to access a Javascript Object dynamicly.
Example:
example: {
name: "dev.pus",
year: 2012,
os: "linux"
}
This isn't anything new. Now you normaly can access properties of the "example" with:
console.log(example.name);
// or
console.log(example.year);
But what is if I want to take the attribute dynamicly?
For example, another var (lets assume the user sets it) should decide which property we want:
var = "name";
console.log(example.var); // error
console.log(example[var]); // error
What is the way to go?
Your example should work if you'll change your variable name (var is reserved).
var key = 'name';
console.log(example[key]);
You can also iterate over your object to get all keys:
for (var item in example){
if (example.hasOwnProperty(item)){
console.log(example[item]);
}
}
http://jsfiddle.net/bC9XJ/