Passing a param to build a JSON object - javascript

How can I pass the subCategory in as an parameter for the function? I have a working solution just passing in the param and then having a switch do the work to make the JSON.subcategory read from the right place. However I feel like there is some thing I am missing on making this more functional, or OO friendly.
So is there a way to make the passed param understand its a variable and not the object literal.
json = {
weather: ["rain", "snow","sun"],
news: ["events", "local","world"]
}
messageBuilder(weather)
function messageBuilder(passedVariable){
var object = json.passedVariable;
// object = json.weather
console.log(JSON.stringify(object));
}
Also am I using the terms correctly? I tried to search google for an answer and ended up not really finding anything.

Just pass the object property key name (sub category) in as a string and use bracket notation to pick it from the data in the function.
Note: that's an object, not JSON, so I've named it as such in the example.
const obj = {
weather: ["rain", "snow", "sun"],
news: ["events", "local", "world"]
};
messageBuilder('weather');
function messageBuilder(subCat){
var object = obj[subCat];
console.log(JSON.stringify(object));
}

Just modify your code a little bit:
json = {
weather : [
"rain", "snow","sun"
],
news : [
"events", "local","world"
]
}
messageBuilder('weather');
function messageBuilder(passedVariable){
var object = json[passedVariable];
// object = json.weather
console.log(object);
}
First of all you should pass your parameter as a string. Then just pull out the property from the object using object['property']

Related

Convert JSON String to Object customizing the Object

I have a JSON string and want to convert it to a an object in javascript, the only issue is the destination object will have different variable names and i want key to assign to a variable and value to a different variable
The JSON would be
{
"Value1":"Type1",
"Value2":"Type2"
}
The object will be
interface Object {
Value: string;
Type: string;
}
I want the JSON to be converted to object array where assigning key (Value1/Value2) to object variable Value and value (Type1/Type2) to object variable Type so the resultant object array would look like below
[{Value: Value1, Type: Type1}, {Value: Value2, Type: Type2}]
Regular JSON.parse wouldn't work as the object is different from json string, any help is appreciated.
You can make use of Object.entries and map:
const obj = {
"Value1":"Type1",
"Value2":"Type2"
};
const result = Object.entries(obj).map(([Value, Type])=>({Value, Type}));
console.log(result);
You can use this:
Object.entries(JSON.parse(json)).map(([Value, Type]) => {
return { Value, Type };
});
Refular JSON.parse works just fine, you just need to do a conversion step after parsing. Break the problem down in multiple steps.
type MyInput = {
Value1: string;
Value2: string;
}
type MyOutput = {
Value: string;
Type: string;
}
function myConversionFunction(input: MyInput): MyOutput {
return {
Value: input.Value1,
Type: input.Value2
}
}
const out = JSON.parse(str).map(myConversionFunction);
This is a great question that I often run into in other languages.
I find it easiest to create a helper function or constructor that maps the appropriate key to the appropriate variables. You take the keys in as parameters and create the object assigning each key to the correct variable.
You will always be mapping the same key name to the same variable name so if you set this mapping once in this helper method and call it for each object it should work correctly for each of them.
I don't actively code in JS. Maybe you thought of this and a reason it doesn't work well?

jQuery - Get value from JSON Stringify

I have a form, that I need to get the values from:
var formConfig = JSON.stringify($("#bookingform").serializeArray());
which returns below:
[{"name":"client_id","value":"1"},{"name":"consignee_id","value":""},{"name":"client","value":"DAKO"},{"name":"model","value":"2"},{"name":"type","value":"2"},{"name":"temperatur","value":"2"},{"name":"shipper_labels","value":"1"},{"name":"batteri_labels","value":"1"},{"name":"batteri_number","value":"2222"},{"name":"pickup","value":"April 27, 2017 18:25"},{"name":"intern_marks","value":"fdsfads"},{"name":"extern_marks","value":"sadsfdsf"},{"name":"consignee","value":""},{"name":"marks","value":""}]
I then need to access above values from the JSON string, which I am using this function to:
var confirmBooking = function(element, setting, correct, notcorrect) {
$('.confirm-booking')
.find(element)
.html(setting === 1 ? correct : notcorrect);
};
The thought is, I can use above function:
confirmBooking('.config_batteri', formConfig.client_id, "Yes", "No");
and so on..
formConfig.client_id should return 1, since that's the value in the JSON string above.
However it returns undefined:
console.log(formConfig.client_id); // Returns "undefined"
You need to use JSON.parse(), to make it a regular JavaScript object again.
What JSON.stringify() does is, as the name implies, make it a string. That is just a regular string, that represents JSON data. It doesn't magically have the JSON data properties.
Furthermore serializeArray() returns an array of {name: ..., value: ...} objects. If you didn't turn it into a JSON string, the result still could not easily be accessed by doing formConfig.client_id. You'd have to loop through the formConfig array, to find the desired name/value pair.
From the looks of it, you don't need to turn the JavaScript object into JSON at all, if you are just going to use it in the same script (unless you are going to send the JSON string somewhere else perhaps).
Based on OP's comments, I'm assuming OP just want to access a particular form element's value. Using jQuery, this can easily be accomplished with:
// get the value of the client_id element (assuming it's an input element)
var client_id = $( '#bookingform input[name="client_id"]' ).val();
// call the function
confirmBooking( '.config_batteri', client_id, "Yes", "No" );
If you want to have an object with all the form values, have a look at the answers in this question.
Do this:
var jsonStr = '[{"name":"client_id","value":"1"},
{"name":"consignee_id","value":""},
{"name":"client","value":"DAKO"},
{"name":"model","value":"2"},
{"name":"type","value":"2"},
{"name":"temperatur","value":"2"},
{"name":"shipper_labels","value":"1"},
{"name":"batteri_labels","value":"1"},
{"name":"batteri_number","value":"2222"},
{"name":"pickup","value":"April 27, 2017 18:25"},
{"name":"intern_marks","value":"fdsfads"},
{"name":"extern_marks","value":"sadsfdsf"},
{"name":"consignee","value":""},
{"name":"marks","value":""}]';
var obj = JSON.parse(jsonStr);
var val = obj[0].value;
The reason you can't do obj[0].name is because your parsed JSON object has a collection of objects, where the first object has this structure:
{
name:"client_id",
value:"1"
}
So, you have to access it using obj[0].value NOT obj[0].name as it would give you client_id.
I think that's what you want.
console.log(formConfig.confirmBooking);
would change of syntax help? please try
console.log(formConfig[0]['client_id']);
I hope it works for you
Since it's an array of objects, you target the first element which returns an object and then use the "value" property to get the actual value of 1 which you expected .
Also use parseInt("1") to get 1 as a type "number"
Hope this solves the issue ! Let me no ASAP
== EDIT
var formConfig = [{
"name": "client_id",
"value": "1"
}, {
"name": "consignee_id",
"value": ""
}, {
"name": "client",
"value": "DAKO"
}];
// This function returns the value for the name
function search(str) {
for (var obj of formConfig) {
if (obj.name == str) {
return obj.value;
}
}
}
search("client_id"); // 1
search("client"); // DAKO

How to access properties of object by dot operator in Javascript

var changeJsonKeyName, newObj, obj;
changeJsonKeyName = function(json, oldName, newName) {
json[newName] = json[oldName];
delete json[oldName];
// json.newName = json.oldName;
// delete json.oldName;
// if i use point in this ,i can not get my result that i want
return json;
};
obj = {
'aaa': '1111',
'bb': {
'cc': 333
}
};
newObj = {};
newObj = changeJsonKeyName(obj, 'aaa', 'nnn');
console.log(newObj);
If I use point here ,I can not get my result that's what I want ,what is the wrong,please help me,thank you very much.
I'm not sure if I understood you correctly, but :
json[newName]
access property named with the value of newName variable
json.newName
access a property named 'newName', which does not exist
First, as a comment points out, this is a Javascript question, not a JSON question.
But you seem to be asking why this works:
json[newName] = json[oldName];
delete json[oldName];
but this doesn't:
json.newName. = json.oldName.;
delete json.oldName;
does not.
And the answer is the second form is actually equivalent to
json["newName"] = json["oldName"];
delete json["oldName"];
In other words, you are dealing with attributes whose names are the constants "oldName" and "newName" rather than attributes whose names are passed as parameters to that method.

How to declare nested objects in JavaScript?

I'm trying to create an object that contains an object, so think of it as a dictionary:
var dictionaries = {};
dictionaries.english_to_french =
{
{english:"hello",french:"bonjour"},
{english:"i want",french:"je veux"},
{english:"bla",french:"le bla"}
};
but it gives the error Uncaught SyntaxError: Unexpected token {
what am I doing wrong?
Thanks !
Edit
I'm sorry that I did not clarify what I want to do.
Edited the code above.
You're trying to give your object a property, and that property will be a single object:
dictionaries.english_to_french =
{english:"hello",french:"bonjour"}
;
You don't need the extra { }. You could declare the whole thing at once:
var dictionaries = {
english_to_french: {
english: "hello", french: "bonjour"
}
};
I would suggest that a better format for your dictionaries might be:
var dictionaries = {
english_to_french: {
"hello": "bonjour",
"chicken": "poulet", // ? something like that
"Englishman": "rosbif"
}
};
That way you can look up words directly without having to search. You could then create the reverse dictionary from that:
dictionaries.french_to_english = function(dict) {
var rv = {};
for (var eword in dict)
rv[dict[eword]] = eword;
return rv;
}(dictionaries.english_to_french);
In order to nest two or more objects, the objects need to have an attribute assigned to them. For example,
{
"hello":{
"english":"hello",
"french":"bonjour",
"portuguese":"ola"
},
"good day":{...},
"how are you":{...}
}
"hello" at the beginning of the object would be the attribute. Then the object is its value. So that way you can access the object by accessing its attribute. Just putting an object in an object does not work. That's why you're getting your error.

Reference another field inside a javascript object

I have an object in javascript:
admins: {
articles: {
path: '/admins/articles',
template: '/views/admins/articles.html',
link: function() {
return path; // !!! how to reference the 'path'?
}
}
}
I have a lot of objects like this, and each of them has a path field and a link function. I want to use the field path in link, but I can't just use path.
What should I do?
You can use this to reference the object. Standard object.method() "dot" syntax will set this to object within method:
var someObj = {
admins: {
articles: {
path: '/admins/articles',
template: '/views/admins/articles.html',
link: function() {
return this.path; // !!! how to reference the 'path'?
}
}
}
};
var returnedPath = someObj.admins.articles.link();
Demo: http://jsfiddle.net/2Pt7n/
(There are other ways to call a function such that this will not be set to the appropriate object, but I hope they don't apply here - you don't really say how you're using the objects or calling the function, but if not in the way I showed then please update your question and I'll update my answer accordingly.)
I'll just point out that you don't want to use ES6 fat arrow here, because there will be no this pointer in that case:
var someObj = {
admins: {
articles: {
path: '/admins/articles',
template: '/views/admins/articles.html',
link: () => {
return this.path; // 'this' is undefined
}
}
}
};
someObj.admins.articles.link() === undefined
What you are showing is not JSON. It is a Javascript object, which is different than JSON. JSON is a strictly defined data serialization format that is a subset of Javascript object literals.
Javascript provides no syntax for referencing peer properties in an object literal, as you want to do. Naming them is one idea, but it won't help, because the name won't exist while the literal is being defined, so the name is not available for you to use in the literal itself.
Also, note that the syntax you define makes the object lop-sided: you can access path as obj.admins.articles.path, but link is a function you would have to invoke: obj.admins.articles.link().
I won't talk about how this is not JSON (others covered it well).
You can do this to get path:
return admins.articles.path;
Here's a fiddle to show it working: http://jsfiddle.net/UwbLt/
I'm reading the answers and even understanding the point of some users (that JSON should be used just for data) and agreeing that this is correct, I just created a proof of concept example. Take a look.
// just a regular object
var obj = {
a: "aaa",
b: "bbb",
c: function() {
return this.a;
}
};
console.log( obj.c() ); // prints "aaa"
// isn't it json just because it has a function? ExtJS will treat it like JSON, but jQuery not
var json = "{" +
"\"a\": \"aaa\", " +
"\"b\": \"bbb\", " +
"\"c\": function() {" +
" return this.a;" +
"}" +
"}";
// ok, the "json" above
console.log( json );
//var jsonObj = $.parseJSON( json ); // does not work
//var jsonObj = eval( json ); // does not work too
var jsonObj = Ext.decode( json ); // it works! shortcut for Ext.JSON.decode
console.log( jsonObj.c() ); // prints "aaa"
It is almost the same that nnnnnn posted, but I think I would post it too, just to complement the answers. jsFiddle: http://jsfiddle.net/davidbuzatto/rhKAM/
So I think, even contradicting the definition of JSON, that JSON maybe can have (or should have?) the same characteristics of a object created using the regular object initializer sintax, since its name is JavaScript Object Notation, not "Lightweight" Object Notation. I know, I know, a deserializer won't be able to deserialize a function depending on the target language, but why ExtJS supports this "behavior"? A good discussion can be found here: Is it valid to define functions in JSON results?
Just to clarify. I don't use (and I won't use too) functions inside my JSONs.

Categories