I was trying the following code :
function doSomething(field, value) {
var someObj = { field : value };
console.log("The object looks like : %j, someObj);
}
I call it like doSomething('emailid', 'a#b.com');
The output was {field : 'a#b.com'}.
How can i make field to take the value from the function call?
Would like to get these values : {'emailid', 'a#b.com'}
Thanks for your time.
When you define an object with the object literal syntax you can either speciy the name of the key as you did, like {field: value} or you can use string literals to define the key such as {"field": value}. Unfortunately there is no way to substitute a variable for a key with object literal syntax, but there is a way to accomplish your outcome.
function doSomething(key, value) {
var someObj = {};
someObj[key.toString()] = value;
return someObj;
}
That should perform your task.
Related
i was asked to write out a piece of code that inverts all key value pairs from an object passed in. this is what i wrote out.
invert(object){
let newObj = {};
for(let key in object){
const original = object[key];
newObj = {original : key}
}
return newObj;
}
aparently that dosent work ( and i cant figure out why). the answer to the question was
invert(object){
let invertedObject = {};
for(let key in object){
const originalValue = object[key];
invertedObject = {originalValue : key}
}
return invertedObject;
}
when ran with with a test file, my code fails while the answer code passes. reasoning was mine is returning undefined.
error code from test :
Failed: _.invert({originalKey: "originalValue"})["originalValue"])
returned undefined instead of originalKey
Difference is in the following statement:
newObj = {original : key}
In your code, when you use original as a key in the newObj, instead of using the value of the original variable as a key, 'original' is used literally as a key.
The original variable is unused in your code.
You can fix the problem by using computed property name as:
newObj = { [original]: key };
Without using the computed property, newObj will be:
{
original:"originalKey"
}
but with computed property name, newObj will be:
{
originalValue:"originalKey"
}
The second code example works because in the following statement
invertedObject = {originalValue : key}
they have used the value of the originalKey as the name of the key. So the key of the returned object will be 'originalValue'.
Also note that the following statement in the second code example
const originalValue = object[key];
is unnecessary because originalValue variable is not being used. Second code example will also work without the above statement.
If second code example uses computed property name as:
invertedObject = { [originalValue] : key }
then you need the statement that declares the originalValue variable.
Personally, I think second code example is error prone and is really easy to break; its also not practical for making a reusable function because:
objects passed to this function won't always have a single key
you won't always know the value of each key in the object and even if you do know the values, if the object has multiple keys, this approach won't work
You should use computed property name which doesn't depends on a variable name being the same as the value of a key in the object.
that inverts all key value pairs from an object passed in
You have to add each property to the same object and not create new object for each property.
function invert(object) {
let newObj = {};
for(let key in object){
const original = object[key];
newObj[original] = key; // add property to same 'newObj' object
}
return newObj;
}
console.log(invert({originalKey: "originalValue", anotherKey: "anotherValue"}))
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']
Let's say I have this function:
var obj = {};
extend('myKey', 'myVal', 'mySomething');
function extend(key, val, something){
$.extend(obj, {
key : {
value: val,
something: something
}); // key is set as "key" and not as the key real value
// I want obj to now have a key which is 'myKey'
// and a value which is an object:
// {value:'myVal', something:'mySomething'}
}
Could this be accomplished somehow?
I would like to do it without creating a new object in the extend function.
var obj = {};
extend('myKey', 'myVal', 'mySomething');
function extend(key, val, something){
obj[key] = {value:val, something:something};
}
//this line is just to show the result of the function, not part of the solution.
document.body.innerHTML += JSON.stringify(obj);
Just use plain JavaScript for this. You can assign a key to an object using the bracket notation. This way you can set it to a variable you defined.
If you are just trying to add properties to obj, you can do this:
function addProp(obj, key, value) {
obj[key] = value;
}
I have a Javascipt object which I use as dictionary
var obj={
xxx:'1'
yyy:'2'
}
However -
xxx and yyy should be a jQuery object.
something like :
var obj =
{
$('#div1'):'1' ,
$('#div2'):'2'
}
is it possible ?
also, How can I get the "value" for key $('#div2') ?
p.s.
I the $.data cant help me here since its also a key value
and i need in the key - object Type also.
Object keys can only be strings ( or Symbol), period. See Member Operators - Property Names # MDN.
Choose a reasonable string representation, and use that. In this case, I'd say the selector string looks like a decent choice:
{
'#div1': '1',
'#div2': '2'
}
also, How can I get the "value" for key $('#div2') ?
Use one of the member operators, either dot notation
var obj = { /* stuff */ };
var value = obj.propertyName;
console.log(value);
or bracket notation (more useful for property names not known until runtime):
var value = obj['propertyName'];
Use a WeakMap which works like a dictionary where the key can be anything. Note that you cannot list all the keys of the map
const aMap = new WeakMap;
const anObject = {};
aMap.set(Number, "It's the Number class")
aMap.set(anObject, "It's an object")
console.log(aMap.get(Number)) // It's the Number class
console.log(aMap.get(anObject)) // It's an object
Is there a way to handle data structures using JSON object in a way of Key/ Value pairs?
If so can some one elaborate how to access associated value object from the key
Assume that I have something like this
KEY1 | VALUE OBJECT1 - (NAME: "XXXXXX", VALUE:100.0)
KEY2 | VALUE OBJECT2 - (NAME: "YYYYYYY", VALUE:200.0)
KEY3 | VALUE OBJECT3 - (NAME: "ZZZZZZZ", VALUE:500.0)
A "JSON object" is actually an oxymoron. JSON is a text format describing an object, not an actual object, so data can either be in the form of JSON, or deserialised into an object.
The JSON for that would look like this:
{"KEY1":{"NAME":"XXXXXX","VALUE":100},"KEY2":{"NAME":"YYYYYYY","VALUE":200},"KEY3":{"NAME":"ZZZZZZZ","VALUE":500}}
Once you have parsed the JSON into a Javascript object (called data in the code below), you can for example access the object for KEY2 and it's properties like this:
var obj = data.KEY2;
alert(obj.NAME);
alert(obj.VALUE);
If you have the key as a string, you can use index notation:
var key = 'KEY3';
var obj = data[key];
var object = {
key1 : {
name : 'xxxxxx',
value : '100.0'
},
key2 : {
name : 'yyyyyyy',
value : '200.0'
},
key3 : {
name : 'zzzzzz',
value : '500.0'
},
}
If thats how your object looks and you want to loop each name and value then I would try and do something like.
$.each(object,function(key,innerjson){
/*
key would be key1,key2,key3
innerjson would be the name and value **
*/
//Alerts and logging of the variable.
console.log(innerjson); //should show you the value
alert(innerjson.name); //Should say xxxxxx,yyyyyy,zzzzzzz
});
JSON (= JavaScript Object Notation), is a lightweight and fast mechanism to convert Javascript objects into a string and vice versa.
Since Javascripts objects consists of key/value pairs its very easy to use and access JSON that way.
So if we have an object:
var myObj = {
foo: 'bar',
base: 'ball',
deep: {
java: 'script'
}
};
We can convert that into a string by calling window.JSON.stringify(myObj); with the result of "{"foo":"bar","base":"ball","deep":{"java":"script"}}".
The other way around, we would call window.JSON.parse("a json string like the above");.
JSON.parse() returns a javascript object/array on success.
alert(myObj.deep.java); // 'script'
window.JSON is not natively available in all browser. Some "older" browser need a little javascript plugin which offers the above mentioned functionality. Check http://www.json.org for further information.
I see what you are trying to ask and I think this is the simplest answer to what you are looking for, given you might not know how many key pairs your are being sent.
Simple Key Pair JSON structure
var data = {
'XXXXXX' : '100.0',
'YYYYYYY' : '200.0',
'ZZZZZZZ' : '500.0',
}
Usage JavaScript code to access the key pairs
for (var key in data)
{ if (!data.hasOwnProperty(key))
{ continue; }
console.log(key + ' -> ' + data[key]);
};
Console output should look like this
XXXXXX -> 100.0
YYYYYYY -> 200.0
ZZZZZZZ -> 500.0
Here is a JSFiddle to show how it works.