I have the below javascript function I want to optimise for my web app.
function DisplayToolTip(str) {
switch (str) {
case "a":
this.tooltip(xvalue,yvalue,text);
break;
case "b":
this.tooltip(xvalue,yvalue,text);
break;
case "c":
this.tooltip(xvalue,yvalue,text);
break;
default: break;
}
}
The switch statement may change i.e. json may need to add in a case "d" but the function exists so dont know how to update the above.
Normally in c# I would use a dictionary, so key would be "a" and value would be an object with properties xvalue,yvalue,text or value would be a string "this.tooltip(xvalue,yvalue,text);".
This way I could update the dictionary and the execution speed of 'DisplayToolTip' would be relatively the same no matter how many elements.
How do you create an array of objects indexed or quickly found using a string value in javascript?
Objects in javascript are like dictionaries.
var dictionary = {
a : ["xvalue","yvalue","text1"],
b : ["xvalue","yvalue","text2"]
}
console.log(dictionary["b"][2]); // will give you text2.
Demo
EDIT: Updated answer to contain arrays (as that is what the question is).
You can use the switch statement itself, with fall-through:
switch (str) {
case "a": case "b": case "c":
this.tooltip(xvalue,yvalue,text);
break;
default: break;
}
(But, as Qantas commented, the default case isn't necessary here.)
Or, it the browser supports it, you can use the indexOf method of arrays:
if (["a", "b", "c"].indexOf(str)) ...
I would do something like this:
var tooltipSettings={
a: {xvalue: 1, yvalue: 1, text: 'string a'},
b: {xvalue: 2, yvalue: 2, text: 'string b'},
c: {xvalue: 3, yvalue: 3, text: 'string c'}
};
function DisplayToolTip(str) {
if(tooltipSettings[str])
{
var settings=tooltipSettings[str];
this.tooltip(settings.xvalue, settings.yvalue, settings.text);
}
}
You could use a dictionary, witch is basically an plain object.
Javascript allows you to access an object property by string like you would access an array property like this:
var obj = {
test: 'text',
b: 4
}
console.log(obj['test'], obj.test);
console.log(obj['b'], obj.b);
So your code would look like this:
var pairs = {
'a': {
xvalue: 1,
yvalue: 1,
text: '1111'
},
'b': {
xvalue: 2,
yvalue: 2,
text: '2222'
}
};
function DisplayToolTip(str) {
var prop = pairs[str];
if (typeof prop !== 'undefined')
return this.tooltip(prop.xvalue, prop.yvalue, prop.text);
throw 'undefined prop ' + str;
}
Related
I wanted to merge nested javascript object. I was simple when I the length of object was one. But since the lenght has increased I need a dynamic way to merge the address key and serialize my object
var old = {account: "100000", address: {city: "LONDON", companyName: "Test IQUE", country: "UK", postalCode: "SW1A 2AA",}, meterName: "DM9"}
When lenght was 1 this worked for me
var new = {
'account' : "100000",
'address' : "LONDON, UK"
'companyName' : "Test IQUE",
'postalCode' : "SW1A 2AA",
'meterName' : "DM90"
},
{
'account' : "1000001",
'address' : "LONDON, UK"
'companyName' : "Test IQUE",
'postalCode' : "SW1A 2AA",
'meterName' : "DM90"
};
Baiscally I need to serialize my nested address object and merge it into one. As the structure of each object will be same I was thinking of using a for each loop which can combine values of address into one.
If you're asking how you can get a full address string from an addresss object, you can use the following code:
'address': Object.values($scope.userDetails.address).join(', ');
The Object.values() function will change your address object into array.
The .join method will concatenate all of the elements from this array into one string. These elements will be separated by a string passed as an argument (, in this case).
You can use lodash lib : https://lodash.com/docs/4.17.15#assignIn
#see
_.assign(object, [sources])
function Foo() {
this.a = 1;
}
function Bar() {
this.c = 3;
}
Foo.prototype.b = 2;
Bar.prototype.d = 4;
_.assign({ 'a': 0 }, new Foo, new Bar);
// => { 'a': 1, 'c': 3 }
_.mergeWith(object, other, customizer);
function customizer(objValue, srcValue) {
if (_.isArray(objValue)) {
return objValue.concat(srcValue);
}
}
var object = { 'a': [1], 'b': [2] };
var other = { 'a': [3], 'b': [4] };
_.mergeWith(object, other, customizer);
// => { 'a': [1, 3], 'b': [2, 4] }
I have:
var obj = {'a': {some object}, 'b': {some other object}, 'c':{some other object},...}
I want to write a function that will overwrite any single key in my original object.
myFunction(obj, {'a': {new object}});
console.log(obj);
//{'a': {new object}, 'b': {some other object}, 'c':{some other object},...}
I am using lodash. I obviously know that I can do _.keys then get the only item in the array and then assign it manually but I wonder if there is a less cumbersome way.
The _.extend function, available as Object.assign in ES6-compatible Javascript, does what you want.
_.extend({ a: 1, b: 2 }, { a: 10 })
// { a: 10, b: 2 }
The function is more flexible than simple assignment: you can add or replace any number of keys, shallow-merging the objects passed as parameters.
No need of Lodash/Underscore, this can be done in JavaScript easily.
obj[key] = newObject;
var obj = {
one: {
1: 'ONE'
},
two: {
2: 'TWO'
},
three: {
3: 'THREE'
}
};
obj['two'] = {
22: 'Two Two'
};
console.log(obj);
UPDATE:
You can use Object.assign()
Object.assign(obj, {
two: {
22: 'Two Two'
}
});
Consider the following two objects:
const source = {
foo: 'value',
bar: 'value',
baz: 'value'
};
const pattern = {
foo: '',
bar: ''
};
_.fn(source, pattern); // { foo: 'value', bar: 'value' }
In this example 'baz' property is deleted because it doesn't exist in the pattern.
_.pick can help
_.pick(source,Object.keys(pattern))
If you want to mutate the original source object for inline key deletion instead of returning a new one, you can do:
_.difference(_.keys(source), _.keys(pattern)).forEach(k => delete source[k])
Or just plain JS:
Object.keys(source)
.filter(k => Object.keys(pattern).includes(k))
.forEach(k => delete source[k])
I generally design for immutability, but this approach might be useful if you want to avoid the overhead of allocating a new object, or you have a lot of primitives that would need copying over by value to a fresh object.
What you can do as well, is look for intersection ofthose two objects:
var a = { 'a': 1, 'b': 2, 'c': 3 };
var b = { 'c': 3, 'd': 4, 'e': 5 };
_.intersection(_.keys(a), _.keys(b)); // ['c']
I am working with JavaScript, could you help me please
Here is my problem.
I have this object:
var MyObj= [{ a: 0, b: "Zero", c: "x", d: "!" }, { a: 1, b: "One", c: "y", d: "#" }]
I want to change the element of selected object ("a" --> "id") to become like this:
var NewObj= [{ id: 0, b: "Zero", c: "x", d: "!" }, { id: 1, b: "One", c: "y", d: "#" }]
I tried to use $.map() method like this
NewObj= $.map(MyObj, function (obj) {
return { id: obj.a, b: obj.b, c: obj.c, d:obj.d };
});
Is there any better way to do this since I only change one element of object?
No need for ES6 / Object.assign, no need for jQuery:
Working Fiddle: https://jsbin.com/gosaqid/edit?js,console
function makeObj(obj){
return obj.map(function(el, i) {
el.id = i;
delete el.a;
return el;
});
}
Not unless you have a clone/copy/extend function available. One is coming up in new JavaScript, and jQuery has one, and it's not very hard writing your own. But it still isn't a walk in the park - you can't just rename a property, you need to copy and delete:
NewObj = MyObj.map(function(obj) {
var newobj = Object.assign({}, obj, {id: obj.a});
delete newobj.a;
return newobj;
});
In your example MyObj is an array of objects.
var object = {}
var array = []
var arrayOfObjects = [{}, {}, {}]
In your desired result, you have changed one of the keys of every object in the array.
Using map is a perfectly adequate way of doing this, in fact JavaScript's array has a built in map method.
var newArrayOfObjects = arrayOfObjects.map(function (obj) {
return {
id: obj.a,
b: obj.b,
c: obj.c
}
})
If you have a ton of keys this can get a little verbose so you can use $.extend, but chances are you're writing code for modern browsers so the whole thing can be written as such:
var newArrayOfObjects = arrayOfObjects.map(obj =>
Object.assign({}, obj, { id: obj.a })
)
update: as #Amadan suggests, you can also delete the old key if you need
var StateValue = {
Unknown: 0,
AL: 1,
AK: 2,
AZ: 3,
AR: 4,
CA: 5,
CO: 6,
CT: 7,
DE: 8,
},
Now i need to get the enumValues.
function getKeyValue(stateVal) {
For example 'AK'
I need to get the corresponding value...
}
To answer the question in the title (in case someone comes for that), and not the one in the description, you can get the key by the value like this:
Object.keys(StateValue).find(
key => StateValue[key] === 2
)
this will return AK
It is simply:
var val = StateValue[stateVal];
You can access object properties with bracket notation.
I suggest to read MDC - Working with Objects.
var val = StateValue.AK would return 2, just like a regular ENUM