FAQ Database Discussion Community


Setting the value of a nested array element based on a dynamic list of keys?

javascript,arrays,recursion,javascript-objects
I have a dynamically-generated object like so (I'm just noting the 'children' array keys here for display purposes, assume its an otherwise syntactically sound array): foo: { children: [ 0: { children: [ 3: { children: [ 6: { //...etc I then have a list of keys being generated: var...

Create two arrays from a collection of object property and values with lodash

javascript,arrays,javascript-objects,lodash
I have an array that contains objects, like this: [{ "first" : 1 }, { "second" : 2 }, { "third" : 3 }] I want to turn this into two arrays, with indexes matching based on these values, such as: ["first","second","third"] [1,2,3] I can iterate through this and get...

Is it possible to have an object method return a function object and if so how do you access it?

javascript,javascript-objects
For instance, if i have: var model = { updateCat: function(cat){ var foo1 = function(){ //do something }; var foo2 = function(){ //do something else }; return{foo1: foo1, foo2: foo2}; } }; model.updateCat.foo1(cat); //does not work What is the best way to do what i am trying to do there?...

Comparing objects from key/value array with another object (Key/value)

javascript,arrays,angularjs,javascript-objects
so here is the situation i currently am having trouble with. I want to check if a user has permission to view a page, with one single function. So I have an array with key/values where i store permissions in. {"authorities":[{"role":"gebruikersbeheer"},{"role":"kijken"},{"role":"plannen"}]}; Stored in service.currentUser, which can be called by using...

Store unstructured JavaScript object in MongoDB with Mongoose+Node.js

node.js,mongodb,mongoose,javascript-objects
In my node.js app, I need to store unstructured JavaScript objects in MongoDB. I have specified following model in Mongoose: module.exports = mongoose.model('DBAllocation', { from: Date, expires: Date, userSession: Object, allocationTimestamp: Date, allocationPriority: Number, vmGroupID: String, allocationRequestContent: Object }); By specifying the data types of userSession and allocationRequestContent to be...

Adding keys to objects in a parse object

javascript,parse.com,javascript-objects
Im working with the parse javascript sdk and i want to add a key to an object in a Parse 'object' when saving it. For ex: var saveGif = new SaveGifTags(); saveGif.save({ type: req.body.type, tag: req.body.tags[i], gifObjects: newGif }, { success: function(data) { console.log(data); res.json(data); }, error: function(data) { console.log(data);...

JavaScript call parent function from child object

javascript,oop,javascript-objects
I am new to Object Oriented Programming with javascript. And trying to implement the basics that we know from other programming languages. I have two classes, one parent and one child. Parent have some private functions and some public functions. Child will inherit parent class. And I wish to access...

React components as plain JS objects?

javascript,class,reactjs,javascript-objects,ecmascript-6
Does anybody has experience in working with React components as plain JS objects instead of annoying ES6 classes and deprecated .createClass method. Maybe you have some examples of factory functions or similar to share? Thanks!...

Javascript call prototype function from function inside constructor

javascript,prototype,javascript-objects
I searched for this issue for quite a long time. Din't find any answer to satisfy my question. What I am trying is: function myClass() { function privateFunction () { publicFunction(); //Error } } myClass.prototype.publicFunction = function() { this.variable = 1; } myClass.prototype.publicFunction2= function() { return this.variable; } This is...

How to add additional objects to an array in Javascript

javascript,arrays,javascript-objects
I am looking to learn how to add an object to array with multiple existing objects following the constructor function which I created. //constructor function function Bookdes(title, author, pages, current_page, available){ this.title = title; this.author = author; this.pages = pages; this.current_page = current_page; this.available = available; } //array of books...

Inherit objects. Iterate through all objects

javascript,oop,javascript-objects
Here is my problem: I have an inherit objects(class) function, which I populate with x many objects, like so: function Booking (doc_id, arrival_date, supplier_amount, client_amount, currency, profit, calculated_profit, currency_rate) { this.doc_id = doc_id; this.arrival_date = arrival_date; this.supplier_amount = supplier_amount; this.client_amount = client_amount; this.currency = currency; this.profit = profit; this.calculated_profit =...

Access public function from private function in JavaScript

javascript,oop,javascript-objects
I have recently started with OOP in JavaScript. And, I am allover confused with these things. I know JavaScript is entirely different from Java. But this is causing problem. What I am trying to implement: function myClass() { //Declare private variable var privateVar = ''; //To act as constructor privateFunction('Hello');...

accessing prototype of javascript object

javascript,javascript-objects
I can access the prototype object of a javascript function using the .prototype but when I cannot use .prototype on a javascript object literal. Please let me know why is this behavior inconsistent. var add = function (a, b) {     return a + b; }; var s={name:'Pradeep'} console.log('Function\'s prototype...

Count properties of multiple objects in array

javascript,arrays,for-loop,javascript-objects
I am looking to count elements in the multi object array. How would I do this? //constructor function function Bookdes(title, author, pages, current_page, available){ this.title = title; this.author = author; this.pages = pages; this.current_page = current_page; this.available = available; } //array of books var bookarrays = [ new Bookdes("Fast Cars",...

javascript object - Dynamically setting a nested value using recursive function

javascript,javascript-objects
I am trying to set one of the nested subobject properties, but the nested level is dynamic. how can I dynamically set the nested properties? It's working only one level properties,i can't set next inner level.... my code: function deSerialize(qualifiedNameArray, currentIndex, resultJSON, valueToBeInitializedForFinalNode) { if (currentIndex == (qualifiedNameArray.length - 1)){...

Unable to select object not part of the initial DOM

jquery,javascript-objects
I have a piece of HTML inserted dinamically with jQuery, by using the .html() method when user clicks on '.acceptExtra': HTML: <div class="tripleButtonsWrap"> <div class="tripleButtonsC"> <div class="acceptExtra"> ............ </div> </div> </div> jQuery: $(document).on('click','.acceptExtra', function(){ closeExtras(); }); function closeExtras(){ $(document).find('.tripleButtonsC').fadeOut(400,function(){ $(this).remove(); $('.tripleButtonsWrap').html(initialCode); //HTML PIECE INSERTED...

Javascript - How to create new instance of functions

javascript,javascript-objects
I know that, we can create the new instance of functions by the following approach. But my question is there any other way to achieve the same? var Person = function (firstName) { this.firstName = firstName; console.log('Person instantiated'); }; var person1 = new Person('Alice'); var person2 = new Person('Bob'); //...

Access Properties of JS Object on Controller

ember.js,handlebars.js,javascript-objects
I have created an Ember.JS application where I hang some properties on the ApplicationController that need to be accessible form all over the app. One of these properties is queue (a JS object) broken down by server names (JS arrays). In my template I would like to list the items...

Javascript Objects and keys

javascript,javascript-objects
The following command shows the properties of an Object. var keys = Object.keys(result); Output: [requester.client.id,request.id] When I try to print an alert(result[request.id]) or alert(result.request.id) I dont get the values. Is there something I am missing?...

What does a [Function] (wrapped in square brackets) mean when inside of a javascript object?

javascript,node.js,javascript-objects
When running console.log on various functions, I'll find properties on the object that have a value of [Function: someFunctionName] in the value section. What does this mean? I want to be able to view the actual code of the function. I'm confused on what's actually being logged when I see...

JavaScript object property assignment

javascript,performance,javascript-objects
On this page -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript " Once created, an object's properties can again be accessed in one of two ways: obj.name = "Simon"; var name = obj.name; obj["name"] = "Simon"; var name = obj["name"]; These are also semantically equivalent. The second method has the advantage that the name of the...

How to create variable with concatenation in javascript?

javascript,oop,variables,object,javascript-objects
I have very long code and want to simplify it. I don't think so we can use string concatination to create different variable name. Is there any other way. If(Something){ var a = some.Test1.x; var b = some.Test1.y; var c = some.Test1.z; var d = some.Test1.p; } If(SomethingElse){ var a...

Dynamically create JavaScript objects with variable depth

javascript,jquery,json,javascript-objects
I'm in trouble with a nasty JSON object that I need to convert to JS object with variable depth. Shortly: (I'm using jQuery) var nastyJSON_string = "{"generics_utenteID":"1","generics_elencoID":"1","mainbar_ade_stepID_0":"1","mainbar_ade_stepID_1":"3","mainbar_ade_stepTitle_0":"blablabla", "mainbar_ade_stepTitle_1" : "quiquoqua"}"; var nastyJSON = JSON.parse(nastyJSON_string); // nastyJSON if parsed correctly now is: {generics_utenteID:"1",generics_elencoID:"1" ...and so on}. Now, I need to convert...

JavaScript - instantiate multiple objects of the same class

javascript,jquery,javascript-objects
I have been attempting to organise my JavaScript/jQuery somewhat better, but am having trouble with objects. Please take a look at this JSFiddle The fundamental pieces are as follows: (function($){ $.toast = function(params) { return new toast(params) } var toast = (function(params){ var params = params; var show = function()...

Extend a JavaScript object with a default function

javascript,arrays,prototype,javascript-objects
In google app scripts I have a one dimensional data array that I can get values from like this: data[0] I'd love to be able to pass in the column name instead like this: data("A") That way I don't have to convert letters into their array position. So I'd like...

javascript undefined variable inside setInterval that is inside function

javascript,javascript-objects
I am having a problem with variable scope. The code below gives me undefined variable error. I could define cursorX directly inside mymodule object. But I guess this is not the right way because I will end up with tens of variables there. Is there any way to declare variable...

Find DOM parent container of JavaScript Object

javascript,jquery,html,object,javascript-objects
Is it possible to traverse up the DOM when looking for the parent container of an image that has been added to a JavaScript object? I have the below object and array of object code: var builtVehicle = {pattern: "../images/fire1192015.png", vehicle: "../images/van1192015.png", wheel: "../images/wheels3.png"}; var createdVehicles = [ {pattern:"../images/checkerboard1192015.png", vehicle:"../images/car1192015.png",...

How to assign key:value pairs from SQL to JavaScript Object using PHP?

javascript,php,sql,javascript-objects
I have the following data in an SQL database cname, ccode, colour Great Britain, GB, 1 Italy, IT, 1 France, FR, 1 Spain, ES, 1 How can I create a JavaScript object like below? var countries = {"GB":1, "IT":1, "FR":1, "ES":1} So far, I have the following code; PHP $query2...

Load Images from within objects with array

javascript,javascript-objects
I have a class that I've created, called Sprite: var Sprite = function Sprite() { that = this; that.xPos = 0; that.yPos = 0; … that.image = null; this.render =function() { … } this.setImage(filename) { that.image = new Image(); that.image.src = filename; } } And then I create an array...

Javascript nested function is not worked

javascript,javascript-objects
I do not understand why the feature does not work , I passed into the method foreach. var methods = { foreach: function(f){ for(var i = 0; i <= this.x; i++){ f(i); } } }; function test(x) { var t = Object.create(methods); t.x = x; return t; }; var t...

Dynamically retrieving JavaScript property value

javascript,javascript-objects
I am trying to dynamically change the options available to a user. A user will choose either 1 or 2. Once they choose a value, I need to load the options associated with that value. Currently, i have the following: var json = {'1':[{ 'value':'A', 'text':'Option - A'}, { 'value':'B',...

Strange JavaScript Object syntax

javascript,google-chrome,internet-explorer,javascript-objects
I recently came accross this in a Library called WebApp.net: var $h = { get HEAD() { return 0 }, get BACK() { return 1 }, get HOME() { return 2 }, get LEFT() { return 3 }, get RIGHT() { return 4 }, get TITLE() { return 5 }...

How to access the properties of a random object in an array?

javascript,arrays,random,javascript-objects
I have an array of objects (I am not so sure if that's the correct way to create it). Each of them have the same properties but different values. I want to access the properties of a random object in this array, but just one time - so when I...

How to pass object properties to a function from object itself?

javascript,oop,javascript-objects
I want to pass an object property to a global function and want to save return value in a new object property . What I tried: var Tools = { id : "tools" , key : myfunc(this.id) //I also tried Tools["id"] and id . }; Here is the function: function...

javascript get inner object from function

javascript,javascript-objects
I have a function in javascript var fn = function(){ var obj = {result: true}; return obj.result; }; I have access to the function, but I need to get the inner obj. Is there a way to do that? EDIT: Thanks to the answers below, I have managed to come...

Object properties are undefined after localStorage

javascript,local-storage,undefined,javascript-objects
I'm storing a bunch of values in localStorage. An array with JSON objects in it to be specific. When I want to add another object to that array here is how I pull it, parse it, push onto the array and set it again. var clickedItem = sessionStorage.getItem('location'), interest =...

Basic JavaScript Syntax

javascript,reactjs,javascript-objects
I have some questions about JavaScript Syntax and looking forward to understand them. First: I don't understand about this syntax below, { Key: () => function() } Example in real project: // Define URL routes // See https://github.com/flatiron/director var routes = { '/': () => render(require('./components/pages/Index')), '/privacy': () => render(require('./components/pages/Privacy'))...

Merging and reordering two arrays of objects

javascript,arrays,object,javascript-objects
I'm trying to figure out how to merge two arrays of objects. Here's what I need to do: field property is the unique identifier of each object Output needs to only have the objects listed in the originalArray Order of localStorageArray needs to be maintained, with attention paid to previous...

Javascript - Defining a Object with Array Properties

javascript,arrays,javascript-objects
I'm not sure how to explain my question. I guess that is why I am not getting good Google search results. Anyway, I would like to create an object with a property that is an array. I tried "this.wrong = null;" as well, and got "undefined" when I ran in...

Accessing JSON attributes within Jade Mixins

json,jade,mixins,javascript-objects
Motivation I have some ugly working code embedded in my Jade template and I want to move it to a mixin so it is more readable, maintainable, etc. The code A simplified equivalent version of the mixing would be: mixin mixinName(param1, param2, paramObject) .tile(class="#{param1 >= paramObject['atr1'] && param1 < paramObject['atr1']...

How can I create methods for json objects in javascript?

javascript,json,methods,javascript-objects
I've created a quiz where every question is a Question object which question has methods like print quiestion and so on. I've added my questions inside the javascript file but I want to move the questions to an external Json file. However I can't find any article that covers how...

jquery each loop through array with multiple objects

jquery,arrays,each,nested-loops,javascript-objects
I have a javascript array of multiple objects like the one bellow : var myArray = [{ year:'2015', model:'BMW', used:false, extras: [{buckets:'no',sportWheels:'yes'},{buckets:'no',sportWheels:'yes'}], color:'blue' ..... }]; What i am trying to do is to loop this array and pass the results into a list, something like this : $.each(myArray, function(i, e){...

Dump JavaScript object including function bodies as “good enough” formattable code

javascript,serialization,javascript-objects,stringify
There are lots of old questions about dumping JavaScript objects. But of the ones which specify dumping the contents of functions, I can only find ones that emit those functions as strings in quotes (with internal quotes escaped). What I want is something that dumps objects, including functions, in full,...

How to reference JavaScript class via “this” within jQuery?

javascript,jquery,reference,this,javascript-objects
Consider the following JavaScript class, property, and method: function Foo() { this.data = 123; } Test.prototype.foo = function() { $("body").append($("<div>") .text("Hello World!") .click(function () { alert("Data: " + this.data); }) ); } var Bar = new Foo(); Bar.foo(); Why is the property data undefined in the alert box? How can...

Eloquent JavaScript, 2nd Edition, Exercise 5.3 Historical Life Expectancy

javascript,arrays,javascript-objects
This problem asks us to take an array of objects (that each contain information about a person), group these people by which century they died in, and then produce the average age a person lived to for each century. I've viewed the textbook solution, but I can't understand why my...

What is Object programming in node js? [closed]

javascript,node.js,object,express,javascript-objects
Strictly speaking what is the OBJECT PROGRAMMING part of node.js ? is it : express.js Javascript node.js itself some programming component ? In theory how can we best define the object programming part of node.js ?...

Access parent properties in angular.forEach

javascript,angularjs,javascript-objects
Here, I created an object say d. var d={ a:"firstName", b:"lastName" }; Now I want to create another object say A, which inherits properties of d. var A=Object.create(d); console.log(A.a);//returns "firstName" console.log(A.b);//returns "lastName" But when I uses console.log(A);// returns empty object, as it doesn't show inherited properties. But it creates little...

Extending Physijs.Mesh

javascript,three.js,javascript-objects,physijs
I am working with Physijs to create a simple fps. Without Physijs I would create a Player object and use the code below to extend the THREE.Mesh class. function Player() { THREE.Mesh.apply(this, arguments); ... } Player.prototype = Object.create(THREE.Mesh.prototype); Then I would instantiate a Player and add the camera to it...

Create an instance of object internally

javascript,javascript-objects
I have tried to create an instance of object internally like the following: var oo = function(){ return new func(); } var func = function(){ this.name; this.age; }; func.prototype = { setData: function(name, age){ this.name = name; this.age = age; }, getData: function (){ return this.name + " " +...

In an array of named objects in javascript - are the names accessible?

javascript,arrays,javascript-objects
If we create some objects, and fill an array with those objects, are the names stored within the array, or only the properties of the object? I guess this may be trivial, but I haven't been able to find an answer. var boxA = {color: "red", width: 100}; var boxB...

Recursive method for checking an object

javascript,javascript-objects
So I have created a constructor that I am attempting to prototype. I want a method that checks through each property in an object to see if its empty and if it is it returns the key. If the property is an object I want it to check through that...

property not functioning properly in my custom constructor - Javascript

javascript,javascript-objects
I'm trying to create a custom constructor in Javascript but I can't seem to get why the Console won't log the 'Letters' property of "Investigating" which was created by the constructor "Verb": function Verb (tense, transitivity) { this.tense = tense; this.transitivity = transitivity; **this.letter1 = this.charAt(0); this.letter2 = this.charAt(2); this.letter3...

Can't access variable in Javascipt object

javascript,object,javascript-objects
I don't understand why I can't access through the b or c variables in the global function of the object object, got some trouble with variables inheritance in JS objects. var object = { a: 'a', global: function() { var b = 'b'; this.c = 'c'; }, render: function() {...

JavaScript two objects - overriding each other

javascript,prototype,javascript-objects
I am trying to learn Object Oriented Programming in JavaScript. Therefore, I may be wrong in what I am doing. I have one JS function (class): function User() { //initiating object code goes here } //Functions User.prototype.getEmpId = function() { return this.empId; } var myUser = new User({'empid':'1'}); console.log(myUser.getEmpId()); //Returns...

Is this correct (JavaScript prototype property)?

javascript,prototype,javascript-objects
Here I created a function which will ultimately be used as a constructor for other clones. Aside from the properties arguments, caller, length, name, __proto__(link to Function.protoype) created, the prototype property is created. This property points to the object which will be assigned as the prototype to the instances created...

working with JavaScript object constructors

javascript,oop,javascript-objects
I'd like to validate property values for when do var obj = new Object(value); and when i do obj.value = newValue. In the methods I've employed below I seem to be able to get one or the other to work, but not both. Is there a way to get both...

Passing method of a constructed object to a function in JavaScript

javascript,javascript-objects
The code below would work in case of regular functions but it doesn't work in case of object methods. I'm getting the following error: return this.anotherService.get1(start, end); ^ TypeError: Cannot read property 'anotherService' of undefined How do I rewrite the code to make getTransactions a general helper function executing different...

How can I retrieve the object into an array in Javascript?

javascript,arrays,object,javascript-objects
I'm currently practicing some basic problem in js and fairly new to any of these languages. I want to retrieve the value and name of the property into an array "temp" from the object "second" if the another obj "third" has the same property value. I can do it, when...

.length of object property accessed through getter and custom toString() is undefined

javascript,javascript-objects
Here is an example JavaScript object: var foo = { valueObj: { value: 'hello', toString: function() { return this.value } }, get val() { return this.valueObj; } } I need to get the length of the string 'hello' stored in foo.valueObj.value. I need to access it with this exact syntax:...

Pushing object to array results in same value

javascript,arrays,javascript-objects,array-push
I have the following javascript code that does not work as I would expect it to. I have a list of checkboxes of which two of the items are "TestDuration" and "AssessmentScores". I'm trying to iterate through the list (which works fine) and have it add the values that are...

Declaring Arrays of Objects within another object

javascript,arrays,javascript-objects
I have recently gotten into javascript (about four days ago), and I'm having troubles acclimating to the syntax a little bit. I'm creating a calender of sorts and I'm trying to get an array of objects (one for each month) to be declared within my "main" object, the calender. I...