How to get objects value if its name contains dots? - javascript

I have a very simple array (please focus on the object with "points.bean.pointsBase" as key):
var mydata =
{"list":
[
{"points.bean.pointsBase":
[
{"time": 2000, "caption":"caption text", duration: 5000},
{"time": 6000, "caption":"caption text", duration: 3000}
]
}
]
};
// Usually we make smth like this to get the value:
var smth = mydata.list[0].points.bean.pointsBase[0].time;
alert(smth); // should display 2000
But, unfortunately, it displays nothing. When I change "points.bean.pointsBase" to something without dots in its name - everything works.
However, I can't change this name to anything else without dots, but I need to get a value? Is there any options to get it?

What you want is:
var smth = mydata.list[0]["points.bean.pointsBase"][0].time;
In JavaScript, any field you can access using the . operator, you can access using [] with a string version of the field name.

in javascript, object properties can be accessed with . operator or with associative array indexing using []. ie. object.property is equivalent to object["property"]
this should do the trick
var smth = mydata.list[0]["points.bean.pointsBase"][0].time;

Try ["points.bean.pointsBase"]

If json object key/name contains dot......! like
var myJson = {"my.name":"vikas","my.age":27}
Than you can access like
myJson["my.name"]
myJson["my.age"]

Related

Removing double quotes from json response

I use basic array to make reference to icons like this:
{name: "text", avatar: srcs[15]}
This works great, but now I dynamically create an array from my json api and it gives me array of objects like this:
{name: "text", avatar: "srcs[15]"}
so I cannot reference to my avatars now. How can I remove double quotes to get my array work again?
Please note that I don't want to get the srcs[15] value to the array, just make a reference to the source array.
The JSON data format does not support references. What you want it not possible.
You need to either:
Put the data you want there explicitly (this may involve duplication) or
Describe the relationship in a way that the program consuming the JSON can interpret as a reference. You could use the reviver argument of JSON.parse to inflate the description back to the data you want to point it to.
JSON is self-contained static data, and it can't reference named variables or objects outside of its own structure.
You can do it like this instead:
{ "name": "text", "avatarIndex": 15 }
And then do one of these to use it:
var avatar = srcs[data.avatarIndex]; // Avatar object in separate variable
// or
data.avatar = srcs[data.avatarIndex]; // Avatar object added into data
You should just put either the value or the whole array , you have also to read about what format json support here
Here's my suggested solutions
var array = [1, 2, 3, 4, 5, 6]
var json1 = {
name: 'test',
value: array
}
console.log("solution 1 :" + json1.value[2])
var json2 = {
name: 'test',
value: array[2]
}
console.log("solution 2 :" + json2.value)

jquery Updating key of a nested object

I've a json string that I've turned into an object with parseJSON (where #get_my_json_data is a textarea to enter json)
var data = jQuery.parseJSON( $("#get_my_json_data").val() );
cool, I've now got an object to see the whole structure.
What I need to do is to alter the KEY of one node. BUT.. I don't know what it is (so can't just do a stringify and search/replace). I DO know the exact position that it'll be...
Here's a sample structure or the json in the textarea.
{
"MasterData": {
"|-|-|ID|-|-|": {
"menu": {
"Tabs": [
{
"Name": "Home",
"TabText": "Home"
},
.........
I need to find the KEY of the second item, in this example, it's: '|-|-|ID|-|-|'
When they edit again, it'll be different. SO how on earth can I update the node key AFTER MasterData and write the whole thing?
I've tried an $.each loop but it just keeps killing the whole 'array'
---- UPDATE ---
I ended up doing this and it worked great!
var data = jQuery.parseJSON( $("#get_my_json_data").val() );
var keys = Object.keys( data.MasterData );
data.MasterData[$(this).val()] = data.ConteMasterDatatData[keys[0]];
delete data.MasterData[keys[0]];
$("#get_my_json_data").val(JSON.stringify(data));
Soo if i understood what you want, you want to replace the property name in the parsed object.
Try this:
//Get the keys
var innerkeys = Object.keys(myObject.MasterData);
//Create a property with the information from the first key
myObject["myNewKey"] = myObject.MasterData[innerkeys[0]];
//Delete old property
delete myObject.MasterData[innerkeys[0]];
If you parse the object to json it should be as you expected (not tested)
Information obtained from:
how-to-list-the-properties-of-a-javascript-object
how-do-i-remove-a-property-from-a-javascript-object

How can I create an object or array of array data in JS with key named elements?

I have an array called values. At present, I'm appending new data to this array as such:
values.push(guests);
The result of my array is something like this:
["123456789", "Joe", "Bloggs", "Test Corp", "fiji", true, "guest, guest 2, guest 3", true]
I have now realised that in its present state this data is useless to me as I cannot tell what each element is. In my example above, the first long number is an account number and the second element is a first name but these are liable to change. E.g the company name Test Corp may not always exist in the data. This means I cannot use the numerical key [3] to target it because it may not be present.
Therefore I need to code this data into something that I can assign both a label for the data, and the data value. I'm guessing the best way to do this would be with an JSON object.
How can I create a key->value pair object? I would need to replace my .push() code above to instead add the value of COMPANY NAME -> Test Corp so that it can be deciphered later.
For reference, I am then stringifying this data and using an AJAX request to POST it to a PHP script where it will need to be arranged into variables e.g $company_name = 'Test Corp';
You're talking about a plain JavaScript object. JSON is a transfer format inspired by JavaScript syntax.
To make an object, just initialize a variable:
var values = {};
And add properties:
values.accountNumber = "123456789";
values.firstName = "Joe";
etc. If you know the properties up front and have values available, you can make the object in one step:
var values = {
accountNumber: "12345678",
firstName: "Joe",
// ...
};

JSON Data format

Not very familiar with JSON data and how to create it using JavaScript.this is what i am trying
i have created two JS variables
var json={};
var json1={};
i have some certain loops to iterate data and loops like
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
json[innerKey]=jsonValues;
}
json1[outerKey]=JSON.stringify(json);
}
Doing this i am getting following output
Required: "{"Center":"radio_Required_Center_0,radio_Required_Center_1,","Left":"radio_Required_Left_0,"}"
which is not a valid JSON format.My idea id to create a outer-key say Required and than an inner one's in my case Center and Left
so that i can iterate each value with respect to key Center (i can break the string based on ')
i am not sure how to create correct structure and i don't want to do it on server side which can be done easily.
any solution or hint will really be helpful.
Edit
var data= JSON.stringify(json1);
giving following output
{"Required":"{\"Center\":\"radio_Required_Center_0,radio_Required_Center_1,\",\"Left\":\"radio_Required_Left_0,\"}"}
which is valid JSON data, now i need to execute some code based on the data in the JSON and here are my requirements
Fetch the outer-key (Required or there can be other also).
Fetch all values under the key Center and Left
Create array from the value retrieved from step 2 (split based on ",").
Loop through the values obtained from step 3 and execute the logic.
My real challenge is at step number 2 and 3 where i need to fetch the keys and its associated values and those key and not predefined so i can not access them based on there name.
I am thinking of a way to get key and its values without hard coding key names and execute my logic.
is it possible in by this approach or not?
If you're using a modern version of Javascript, it comes with JSON functions built-in.
var jsonString = JSON.stringify(jsobject);
...to convert a JS object into a JSON string.
(See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify)
and
var jsOject = JSON.parse(jsomString);
...to convert back in the other direction.
(see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse)
The only time you need to worry about this not being built-in is if you're using an old browser - for example, older versions of IE. However, in this case, there are polyfill libraries like this one that you can load which will implement the above syntax for you.
If you're just trying to compose one big JSON object, you don't need to stringify one JSON object before adding it to another... So instead of doing JSON.stringify(json) you can just do json1[outerKey]=json
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
json[innerKey]=jsonValues;
}
json1[outerKey]=json;
}
try jsonlint.com to validate your JSON
This is valid:
{
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
This is valid too:
{
"Required": {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
}
This isn't:
Required: {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
using JSON.stringify() is the right way of converting javascript objects to JSON string format. However if you want to put it in a variable you should do that first, later in the last step you convert to JSON string.
var output = { "Required": yourpreviousjsonvar },
jsonString = JSON.strinify(output);
EDIT:
You need to process the data first you probably won't even need the JSON string if I understand you right. (=> if however you already got a string you need it parsed first. Do it using JSON.parse(yourjsonstring))
Fetch the outer-key (Required or there can be other also).
Fetch all values under the key Center and Left
Create array from the value retrieved from step 2 (split based on ",").
Loop through the values obtained from step 3 and execute the logic.
having this as variable:
var a = {
"Required": {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
}
// step 1
console.log(a.Required);
// step 2
console.log(a.Required.Center);
console.log(a.Required.Left);
// step 3
var center = a.Required.Center.split(',');
var left = a.Required.Left.split(',');
// step 4
for(var i = 0; i<center.length; i++){
console.log("doing somthing with", center[i]);
}
Here is a fiddle => use Chrome/safari/Opera's developpertools and check the console to check the output. Or use firebug (in firefox) Or IE9 or greater (F12).
Use native Javascript toSource :
var obj= new Object();
var obj1= new Object();
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
obj.innerKey=jsonValues;
}
obj1.outerKey=obj;
}
json = obj.toSource();
json1 = obj1.toSource();

push values into an array dynamically with javascript

I'm have trouble finding a way to push values into an array dynamically. I have given the following situation:
var get_anchors= new Array('pitzel','mitzel','sizzle')
current_anchor= pics[key].anchor; //has the value 'sizzle'
get_anchors[current_anchor].push(new Array('sizzle2','sizzle3'))
Javascript fails and says get_anchors[current_anchor] is undefined
How can I make get_anchors[current_anchor] work. Or is there a different way to get this done?
The desired result should look like 'pitzel','mitzel','sizzle'['sizzle2','sizzle3]
Based on your comment it looks like you want a hash map instead of an array. You can use an object for this:
var anchors = {
'pitzel': [],
'mitzel': [],
'sizzle': []
};
Then you can do:
anchors[current_anchor].push('sizzle2', 'sizzle3');
or assuming that anchors does not have a property with the value of current_anchor, simply assign a new array:
anchors[current_anchor] = ['fooX', 'fooY'];
Of course you can populate the object dynamically as well. Have a look at Working with Objects for more information.
I'm not sure I understand what you're trying to do, but I think you're trying to insert a few elements after where another occurs. This will do the trick:
var get_anchors = [ 'pitzel', 'mitzel', 'sizzle' ];
current_anchor = get_anchors.indexOf(pics[key].anchor);
get_anchors.splice(current_anchor + 1, 0, 'sizzle2', 'sizzle3');
// get_anchors = [ 'pitzel', 'mitzel', 'sizzle', 'sizzle2', 'sizzle3' ]

Categories