How to insert object inside an object in javascript? - javascript

I'm trying to insert an object inside another object and with what I tried I wasn't successful in any of the, let's say I want to insert an object inside an object, these are the ways I tried:
var ob = {
user1: {name: 'chris'}
};
1:
ob['user2']['name'] = 'Luana'; //error
2:
var obA = ob['user2'];
obA['name'] = 'Luana'; //error
3:
ob['user2'] = ['name'] = 'Luana'; //error
These are the ways I tried, but since I am not successful, how can I insert other properties, other than this way below?
obA['user2'] = {name: 'Luana'}; // for me this is not what i'm looking for
My wish is to make the code below:
var gentleman = {};
var test = 0;
onclick = () => {
test = 1;
gentleman ['names'] [test] = 'I am a gentleman' test
console.log (gentleman);
}
Return this result:
gentleman = {
names: {
1: 'Im gentleman 1',
2: 'Im gentleman 2',
3: 'Im gentleman 3',
...
}
}
Note
What I'm doing is, create a piano and each key prepreced I create a new audio with new Audio and pass the url of this key itself, so far so good, the problem needs some logic to check if the audio is already was called, the logic I thought was the following:
When the user clicks on the key I insert into a notes_ object the property with the key of the C or D ... key is the value of the new Audio audio, each key I insert into this same notes_ object that is inside another songs_ object. As I saw in several answers, when adding as mentioned in them, the values ​​that are in the object are reset, but that's not what I want;
Check it out
var songs_ = {
music1 = 'name',
music2 = 'name',
notes_ = {}
};
Each key I press, I'll add a property to notes_ like this:
var key_ = new audio(urlNote);
note 1 C = key_;
notes_ = {
C = key_, //(here contains the audio of the note itself C)
C_ = key_,
D = key_,
...
} // the content here should not be changed, just added

Update after updated question
var gentleman = { names:{}};
var test = 0;
document.getElementById("btn").addEventListener("click", function() {
test++
gentleman ['names'] [test] = `I am a gentleman ${test}`
console.log (gentleman);
})
<button id="btn" type="button">Click</button>
Old answer:
the key I'm trying to enter is a variable eg: var key = 'user'; var keyI = 'name'; ob[key][keyI] = 'name'
Perhaps you meant this?
var obj = {
user1: {
name: 'chris'
}
};
console.log(obj)
let key = 'somekey'
let key1 = 'someotherkey'
let val = 'somevalue'
obj[key] = {[key1] : val}
console.log(obj)

There is another regularly way.
You could try this:
var ob = {
user1: {name: 'chris'}
};
var ob2 = {
user2: {name: 'Luana'}
};
var result = Object.assign(ob, ob2);
console.log(result);

Not possible in that way.
var ob = {
user1: {name: 'chris'}
};
//If you wanna do this, it will show you an error since 'user2' does not exists on ob:
ob['user2']['name'] = 'Luana'
// So yo wanna create it first:
ob['user2'] = {name: 'chris'};

Related

Access dynamically created objects in Javascript

I am attempting to dynamically create an object with name-value pairs using html input fields. This is what i have so far:
var taskComplete = {
newTask: function(arg) {
var fieldObj = {},
selector = arg,
inputFields = document.getElementsByClassName(selector);
for (var i=0;i<inputFields.length;i++) {
var attrValue = inputFields[i].getAttribute("name"),
value = inputFields[i].value,
newFieldObj = fieldObj[i] = {[attrValue]: value };
console.log(newFieldObj);
}
}
}
taskComplete.newTask('input');
The console log outputs:
Object {title: ""}
Object {description: ""}
Object {date: ""}
Question1:
How do i access these objects? they all share the same name eg. 'Object' so 'object.title' does not work.
Question2:
Is there a way to combine these objects into a single object?
eg.
var obj = {
title: "",
description: "",
date: "",
}
code example with html: codepen.io
Hope this make sense. Thank you for any and all assistance.
I will answer your questions in the reverse order, makes more sense, you will see.
Question2: Is there a way to combine these objects into a single object?
Yes, I am happy to inform you that you absolutely can. Where you do
newFieldObj = fieldObj[i] = {[attrValue]: value };
simply do
fieldObj[attrValue] = value;
What this does, is the following: On the fieldObj, which is a plain {} set a key named after the value of attrValue and pair that key with the value value
Question1: How do i access these objects? they all share the same name eg. 'Object' so 'object.title' does not work.
In order to be able to access these objects, your newTask method should be returning them. So, at the end of your newTask method, simply do return fieldObj; like so
var taskComplete = {
newTask: function(arg) {
var fieldObj = {},
selector = arg,
inputFields = document.getElementsByClassName(selector),
attrValue,
value;
for (var i=0;i<inputFields.length;i++) {
attrValue = inputFields[i].getAttribute("name");
value = inputFields[i].value;
fieldObj[attrValue] = value;
}
return fieldObj;
}
}
and then store the returned value to a new variable like so:
var aFancyName = taskComplete.newTask('input');
Here's the modified pen: http://codepen.io/anon/pen/XdjKQJ
Not super clear on what you are trying to do here.
Instead of creating a new object for each iteration of your loop, why not just assign those properties to the fieldObj you already have?
Then you can just return that object and do whatever you want with it in the calling code:
'use strict';
// ** TASK OBJECT ** //
var taskComplete = {
newTask: function(selector) {
var fieldObj = {},
inputFields = document.getElementsByClassName(selector);
for (var i = 0; i < inputFields.length; i++) {
var attrKey = inputFields[i].getAttribute("name"),
value = inputFields[i].value;
fieldObj[attrKey] = value;
}
return fieldObj;
}
}
var o = taskComplete.newTask('input');
console.dir(o);
http://codepen.io/anon/pen/reMLPB?editors=0010

Real use case dynamic (computed) property

A dynamic property:
var obj = {
// Computed (dynamic) property names
[ 'prop_' + (() => 42)() ]: 42
};
This is of course very fancy. But where could someone use this without adding unnecessary complexity?
If you have a property name as a constant:
var obj = { [SOME_CONSTANT]: 42 };
One case where I wanted it was where property names for JSON were defined in generated files, based off Java classes.
// Generated
var SomeJsonBodyParams = {NAME: 'name', ID: 'id', ETA, 'estimatedTimeOfArrival'};
// Using it
sendAjax('some/url', {
[SomeJsonBodyParams.NAME] = userData.name,
...
});
We even had a method so we could kind of do it
function makeObj() {
var obj = {};
for (var i=0; i < arguments.length; i+=2) {
obj[i] = obj[i+i];
}
return obj;
}
sendAjax('some/url', makeObj(
SomeJsonBodyParams.NAME, userData.name,
...
));
You can use it in class and with Symbols:
class MyClass {
[Symbol.iterator]() {
// my iterator
}
}
Let's say you have:
var hi = 'hi';
var test = 'test';
var hello = 'hello';
Instead of:
var object = {};
object[hi] = 111;
object[test] = 222;
object[hello] = 333;
You could write it in a much shorter syntax:
var object = {
[hi]: 111,
[test]: 222,
[hello]: 333
}
E.g. it could be used when you want to use a, let's say, constant as a key in object.
const DATA_TYPE = {
PERSON: 'person',
COMPANY: 'company'
};
let cache = {
[DATA_TYPE.PERSON]: getPerson()
};
And later access:
cache[DATA_TYPE.PERSON]
Instead of DATA_TYPE.PERSON could be anything (including some real-time calculated values).

Parameter name in object when its created

I want to get parameter name when a function applied as new. I have search but i couldn't find what i am exactly looking.
Here is a sample;
var myobject = function(){
/*I need "param" in here as string*/
}
var param = new myobject();
thanks for any idea or referance without any library.
the original case code is:
var selectQueue = [];
var queue = function(data){
this.defaults = {
name: "base",
type: "fifo"
}
this.availableTypes = ["fifo","lifo","random"];
if(!data){data = {};}
for(param in this.defaults){
if(!data[param]){
data[param] = this.defaults[param];
}
}
/*this is what i want to do with dynamic name*/
selectQueue.push({
a:this
});
}
var a = new queue();
What you want is not really possible in JS, but a possible workaround is to send the name you want to the constructor, such as:
var selectQueue = [];
var queue = function(data, name){
this.defaults = {
name: "base",
type: "fifo"
}
this.availableTypes = ["fifo","lifo","random"];
if(!data){data = {};}
for(param in this.defaults){
if(!data[param]){
data[param] = this.defaults[param];
}
}
var o = {};
o[name] = this;
selectQueue.push(o);
}
var a = new queue(data, 'a');
Another possibility is to keep track of the current index of selectQueue.
The object has properties and this is the syntax.
var myObject = function(){
name: "your name",
age: 19,
hobby: "football"
}
var param = myObject.name;
That is the way you define a property.

Javascript - get object value using variable

I'm trying to get an object value by passing a variable to a function, but I'm not sure how to do this with a multi layer object. It looks like this:
var obj = {
field1: { name: "first" },
field2: { name: "second" }
};
var test = function(field){
//sorting function using obj[field]
//return results
};
With the above, the following works:
var result = test("field1");
This sorts using the object {name: "first"} but say I want to use just the name value. I can't do this:
var result = test("field1.name");
What is the correct way to do this?
what about this?
var result = test("field1", "name");
var test = function(field, keyname){
return obj[field][keyname];
};

Concatenate object field with variable in javascript

I'm building an object in javascript to store data dynamically.
Here is my code :
var id=0;
function(pName, pPrice) {
var name = pName;
var price = pPrice;
var myObj = {
id:{
'name':name,
'price':price
},
};
(id++); //
console.log(myObj.id.name); // Acessing specific data
}
I want my id field to be defined by the id variable value so it would create a new field each time my function is called. But I don't find any solution to concatenate both.
Thanks
You can create and access dynamicly named fields using the square bracket syntax:
var myObj = {};
myObj['id_'+id] = {
'name':name,
'price':price
}
Is this what you want ?
var myObj = {};
myObj[id] = {
'name':name,
'price':price
};
console.log(myObj[id]name); // Acessing specific data
You can use [] to define the dynamic property for particular object(myObj), something like
var myObj = {};
myObj[id] = {'nom':nom, 'prix':prix};
Example
function userDetail(id, nom, prix) {
var myObj = {};
myObj[id] = {'nom':nom, 'prix':prix};
return myObj;
}
var objA = userDetail('id1', 'sam', 2000);
var objB = userDetail('id2', 'ram', 12000);
var objC = userDetail('id3', 'honk', 22000);
console.log(objA.id1.nom); // prints sam
console.log(objB.id2.nom); // prints ram
console.log(objC.id3.prix);// prints 22000
[DEMO]

Categories

Resources