Assigning objects to keys inside a JavaScript object - javascript

I want to create an object like this:
var servers =
{
'local1' :
{
name: 'local1',
ip: '10.10.10.1'
},
'local2' :
{
name: 'local2',
ip: '10.10.10.2'
}
}
This is what I'm doing
$.each( servers, function( key, server )
{
servers[server.name] = server;
});
Where servers is an array of objects like these:
{
name: 'local1',
ip: '10.10.10.1'
}
But the code above does not assign any keys to the object, so the keys default to 0,1,2....

One potential bug I notice is that you're modifying the object that you are iterating over (servers). It might be good to create a new empty object that you modify in the loop.
Also, it'd help if you posted some sample data so we can run your code for ourselves.
Finally, you could try inserting a debugger keyword in there and stepping through the code.

In Chrome if You run this:
a = [];
b = {n:"c",i:"1.2.3.4"};
a[b.n] = b;
alert (a["c"].i);
alert (a.c.i);
You will got the "1.2.3.4" string as expected. But if you change the example as:
a = {};
b = {n:"c",i:"1.2.3.4"};
a[b.n] = b;
alert (a.c.i);
You will get the same "1.2.3.4" again :). So the answer is: your code assigns the properties to the objects as you asked. The only difference is that in the first example you used the array as object, and in second the simple object.

AFAIK [] in javascript is used to index arrays, while to access object properties you have to use dot notation. So your code should be:
$.each( servers, function( key, server )
{
var name = server.name;
eval("servers." + name + " = server");
});
Please try it out since I don't test it.

Related

How do I set multiple values of a JSON object?

So I've been working on this project but I'm stuck because I can't figure out how I should go about setting the other values of this new JSON object. So basically on the front end I have this:
HTML page view. The 'cat4' ID is the new object I tried to create, and illustrates the error I'm trying to fix. The problem is that I'm having trouble setting the LIMIT value of newly created objects (or multiple values at all). Here is the code where the object is created:
function sendCat()
{
window.clearTimeout(timeoutID);
var newCat = document.getElementById("newCat").value
var lim = document.getElementById("limit").value
var data;
data = "cat=" + newCat + ", limit=" + lim;
var jData = JSON.stringify(data);
makeRec("POST", "/cats", 201, poller, data);
document.getElementById("newCat").value = "Name";
document.getElementById("limit").value = "0";
}
In particular I've been playing around with the line data = "cat=" + newCat + ", limit=" + lim; but no combination of things I try has worked so far. Is there a way I can modify this line so that when the data is sent it will work? I find it odd that the line of code works but only for setting one part of the object.
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
MDN
I think this is what you want:
const newCat = 'Meow';
const newLimit = 5;
const data = {
cat: newCat,
limit: newLimit
}
console.log(JSON.stringify(data));
What you're referring to as a 'JSON object' is actually just a javascript object, you can make one using object literal syntax. An object literal with multiple properties looks like this:
var data = {
cat: newCat,
limit: lim
};
makeRec("POST", "/cats", 201, poller, JSON.stringify(data));
assuming the fifth parameter to makeRec is supposed to be the POST request body as stringified JSON, as your code seems to imply

JavaScript selecting Object Arraylike?

The Problem is the following:
I have a JSON file that has objects with the following name: "item0": { ... }, "item1": { ... }, "item2": { ... }. But I can't access them when going through an if method.
What I've done so far:
$.getJSON('/assets/storage/items.json', function(data) {
jsonStringify = JSON.stringify(data);
jsonFile = JSON.parse(jsonStringify);
addItems();
});
var addItems = function() {
/* var declarations */
for (var i = 0; i < Object.keys(jsonFile).length; i++) {
path = 'jsonFile.item' + i;
name = path.name;
console.log(path.name);
console.log(path.type);
}
}
If I console.log path.name it returns undefined. But if I enter jsonFile.item0.name it returns the value. So how can I use the string path so that it's treated like an object, or is there an other way on how to name the json items.
As others stated 'jsonFile.item' + i is not retrieving anything from jsonFile: it is just a string.
Other issues:
It makes no sense to first stringify the data and then parse it again. That is moving back and forth to end up where you already were: data is the object you want to work with
Don't name your data jsonFile. It is an object, not JSON. JSON is text. But because of the above remark, you don't need this variable
Declare your variables with var, let or const, and avoid global variables.
Use the promise-like syntax ($.getJSON( ).then)
Iterate object properties without assuming they are called item0, item1,...
Suggested code:
$.getJSON('/assets/storage/items.json').then(function(data) {
for (const path in data) {
console.log(data[path].name, data[path].type);
}
});
What you want is to use object notation using a dynamic string value as a key instead of an object key. So, instead of using something like object.dynamicName you either have use object[dynamicName].
So in your example it would be like this.
path = 'item' + i;
jsonFile[path].name
I'm afraid you cannot expect a string to behave like an object.
What you can do is this:
path = `item${i}`
name = jsonFile[path].name

Store values in javascript object with same keys

I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];

Better way to build JSON array and retrieve its elements

Here's how I'm initializing and building an array:
var newCountyInfo = new Object();
newCountyInfo.name = newCountyName;
newCountyInfo.state = newCountyState;
newCountyInfo.zips = newCountyZips;
newCountyInfo.branchID = newCountyBranchID;
So I have my four elements in the array. I'm then passing newCountyInfo to another function to pull out the elements for display in some HTML elements.
The only way I know how to get to the individual elements in the function that uses them is this:
JSON.parse(JSON.stringify(newCountyValidation)).name
JSON.parse(JSON.stringify(newCountyValidation)).state
... etc...
There's got to be a better/shorter/more elegant way of doing this!
What is it?
Why are you serializing at all? I don't understand what JSON has to do with this, unless you're using web workers, ajax, or something else which demands serialization. Start with object literal syntax:
var newCountyInfo = {
name: newCountyName,
state: newCountyState,
zips: newCountyZips,
branchID: newCountyBranchID
};
And just pass the whole object to the other function:
someOtherFunction(newCountyInfo);
Which can access the fields using plain old property accesses:
function someOtherFunction(foo) {
console.log(foo.name); // whatever was in newCountyname
}
No JSON whatsoever.
Something like this should work just fine:
var newCountyInfo = {
name: newCountyName,
state: newCountyState,
zips: newCountyZips,
branchID: newCountyBranchID
}
function test(newCountyValidation)
{
alert(newCountyValidation.name);
}
test(newCountyInfo);

Length of and iterating array that is using custom properties

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.

Categories