Extended function jquery - javascript

I have a function that looks like this:
jQuery.fn.menuFunc = function( settings ) {
settings = jQuery.extend({
actionAddURL:"",
actionModifyURL:"",
........
},settings);};
where all the parameters i initialize (actionAddURL, actionModifyURL, etc..) are strings (ids of different elements or urls). My question is how do i add some objects there.
myObject:"" doesn't seem to be the way to do it. Any tips?

myObject:[] // empty JavaScript object
,
myOtherObject: { // JavaScript object notation
name: "Bob",
age: 17
}

Probably:
myObject: {}
is what you are looking for.
You can then add properties to it:
myObject.name = "Name";

To define an object you could use the following syntax:
myObject: { stringProp: 'value1', intProp: 10, arrayProp: [ 1, 2, 3 ] }

Related

Is it possible to have an associative array in Vue.js without using an object?

I'm trying to get an associative array but this syntax produces an error as the lamda sign. How would I do this? I would like to avoid using an object because the key needs to be a string that has capital letters and spaces.
<script>
export default {
name: 'VueHeader',
data() {
return {
links : ['Dashboard' => '/dashboard', 'Account' => '/account'],
}
}
}
</script>
<script>
export default {
name: 'VueHeader',
data() {
return {
links : {'Dashboard': '/dashboard', 'Account': '/account'},
};
}
}
</script>
JS Objects can use strings as keys. These will meet your needs because 'Foo' !== 'foo'. Take the following example:
> x = {"foo": 10, "Foo": 20, "foo bar": 15}
{ foo: 10, Foo: 20, 'foo bar': 15 }
> x['Foo']
20
> x['foo']
10
> x['foo bar']
15
As another answer correctly states, plain objects act as associative arrays in JavaScript:
...
links : {'My Dashboard': '/dashboard', 'My Account': '/account'},
...
Keys can be arbitrary strings. In case a key contains spaces or other non-alphanumeric characters, it can be accessed with bracket notation. Since it's fundamental JS feature, it's supported in Vue templates:
{{links['My Dashboard']}}
The problem with plain objects is that specs don't guarantee the order of keys, although it's de facto preserved in all current implementations.
A modern alternative that guarantees the order is ES6 Map. It's currently non-reactive in Vue and can substitute plain object only for static data:
...
links : new Map([['My Dashboard', '/dashboard'], ['My Account': '/account']]),
...
Since there is no such thing as associative array in javascript, an array must always have it's integer indexes in an incrementing order.
Instead of that, you can just create an object instead and access the property in array notation as such:
const obj = { 'Dashboard': '/dashboard', 'Account': '/account' };
console.log(obj['dashboard']);
console.log(obj['Account']);

Add object to another object property in JS

obj={
cats:{name:"kitty",age:"8"}
}
I need to add {name:"nacy",age:"12"} to obj.cats how I can do that?
What I tried:
Object.assign({name:"nacy",age:"12"},obj.cats);
This doesn't do anything, when I console.log(obj) I got kitty only.
In the end I want when I console.log(obj.cats) to get this:
{name:"kitty",age:"8"}, {name:"nacy",age:"12"}
And I don't want to use arrays.
It would be advisable to read more the documentation on objects and arrays. object.cats should be an array. Correct usage:
let obj = {
cats: [
{name:"kitty",age:"8"}
]
};
obj.cats.push({name:"nacy",age:"12"})
//Now here, we have 2 elements of obj.cats
console.log(obj.cats)
If you want to use objects and replace obj.cats (as your example), you must first pass the existing object, and then the value to replace: Object.assign(obj.cats, {name:"nacy",age:"12"})
if you wanna add 'nacy' first you have change cats to become an array
(read more about array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
it looks like this:
var obj={
cats:[{name:"kitty",age:"8"}]
}
and then 'push' or add 'nacy'
obj.cats.push({name:"nacy",age:"12"})
result :
{ cats: [ { name: 'kitty', age: '8' }, { name: 'nacy', age: '12' } ] }

Dexie : How to add to array in nested object

I am using Dexie IndexedDB wrapper and I am trying to add an object to an existing array which in inside a nested object. The structure looks similar to below
{
Name : 'John',
age : 33,
tags : {
skill: [{
first: '.NET',
second: 'JAVA',
third: [{special1:'sleep'},{special2:'eat'}]
}]
}
}
I have tried many way to push object special3:'run' to skill.third but without success. My last attempt looked something like this
const pathObject = {};
const fullPath = 'result.tags.skill[3].third';
pathObject[fullPath] = {special3:'run'};
db.inspections.update(id, pathObject);
The object is added outside and not inside the array 'third' something like below
{
Name : 'John',
age : 33,
tags : {
skill: [{
first: '.NET',
second: 'JAVA',
third: [{special1:'sleep'},{special2:'eat'}]
}]
skill[3]: {
third: {special3:'run'}
}
}
}
I wish to know if there a way to add to arrays in nested object using Dexie if not is there a way to achieve this using indexeddb. Help is appreciated as problem is been holding back progress
The easiest is to use Collection.modify() with a callback function to mutate your model:
db.inspections.where('id').equals(id).modify(x =>
x.tags.skill[0].third.push({special3:'run'}) );
If you want to use a keypath containing array items, it is also possible, as arrays can be looked at as objects with numeric keys:
db.inspections.update(id, {"tags.skill.0.third.3": {special3:'run'}});

Angular unintentional binding/object mirroring

So I am working on a project using AngularJS where I need to be able to compare the values of an object in the scope with it's previously recorded values. I'm doing this through an algorithm such as the one below:
function() {
var data = [
{ id: 1, key: 'value', foo: 'bar'},
{ id: 2, key: 'value', foo: 'bar'}
]
$scope.oldTarget = data[0];
$scope.target = data[0];
}
Now if I were to do:
function() {
$scope.target.foo = 'fighters';
if ($scope.target != $scope.oldTarget) console.log('Target was modified');
console.log($scope.target);
console.log($scope.oldTarget);
}
It will output:
{ id: 1, key: 'value', foo: 'fighters'}
{ id: 1, key: 'value', foo: 'fighters'}
My assumption is that AngularJS is automatically binding the two variables target and oldTarget and mirroring any changes done to target to oldTarget. Is this the case, and if so, is there anyway for me to prevent this? If not, what am I doing that's causing it to do this?
This is not related to Angular, it's default JavaScript behavior. You are referencing the same object. If you intend to modify it without changing the source, you need to clone the object.
Take a look:
What is the most efficient way to clone an object?
Most elegant way to clone a JavaScript object
I assume that this is not angular, this is just how it works, because $scope.oldTarget and $scope.target both is links to the same object.
var test = {foo : 'bar'};
var newTest = test;
newTest.foo = 'changed';
console.log(test);
Th output is: "Object {foo: "changed"}"
http://jsfiddle.net/rf0ac6zf/
Looks like your array element is being referenced "by reference". So create new instances of the element like this:
$scope.oldTarget = $.extend(null,data[0]);
$scope.target = $.extend(null,data[0]);

Using objects to store a list of names

I was wondering how to use an object to store a list of different names and access them by simply using the key.
Do I have to use embedded object like this.
var f =
{
0 : { name : "John" },
1 : { name : "Phillip" }
};
console.log(f[1].name);
Do not over-complicate things. Why don't you just try a simple array?
var f = [
{ name : "John" },
{ name : "Phillip" }
];
console.log(f[1].name);
Why not just an array, which is indexed identically? Do you actually need a name: attribute for some reason?
var names = [ 'John', 'Phillip' ];
Instead of names[0].name, which is pretty redundant, you'd just use names[0]...
He wants to access them by key:
var people = {
John:{ age:33},
Bob :{ age:42}
};
Now you can truly access them by key:
console.log(people["John"].age);
or this way (although odd):
console.log(people.John.age);
No looping is necessary, you are using the power of javascripts associative syntax to index directly into your data structure. No need to refer to some arbitrary integer index either.
This definitely works but typically you'd use a more appropriate property to index than just a name like perhaps an employee id.
You can use like this
Var names = [
{ 'name' : 'ashwin', age: 18 },
{'name' : 'jhon', 'age' : 20 }
];
console.log ( names[0].name );

Categories

Resources