Javascript - get object value using variable - javascript

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];
};

Related

How to insert object inside an object in 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'};

How to put object inside another object using javascript

var noOfChild=document.getElementById('btnInput').value;
for(var i=1;i<=noOfChild;i++){
createJSON();
function createJSON() {
alert('working')
var jsonObj =[];
var startId=1;
$("span[id=childNo]").each(function() {
var idChildName='childName'+startId;
var childName=document.getElementById(idChildName).value;
var idDobChild='dobChild'+startId;
var dobChild=document.getElementById(idDobChild).value;
var idSchoolName='schoolName'+startId;
var schoolName=document.getElementById(idSchoolName).value;
var idClassSection='classSection'+startId;
var classSection=document.getElementById(idClassSection).value;
alert(childName);
var item = {};
item ["child_name"] = childName;
item ["child_DOB"] = dobChild;
item ["child_class"] = classSection;
item ["child_school_name"] = "KV_32";
// jsonObj.push("{'"+startId+"':['"+item+"']}");
jsonObj.push(item);
startId=startId+1;
});
var obj={
"1":jsonObj
};
console.log(obj);
I want object like this:
{"1":{"child_name": "ytfy", "child_DOB": "1993-06-18", "child_class": "d", "child_school_name": "KV_32"}}
But i am getting like this:
1:{child_name: "ytfy", child_DOB: "1993-06-18", child_class: "d", child_school_name: "KV_32"}
This implementation in my opinion is a lot cleaner and nicer to see. The only thing you have to understand is that by calling objectResult["1"] you also create a field "1"
var object = {"childName":"foo", "childSurname":"foo"};
var objectResult = {}
objectResult["1"] = object;
console.log(objectResult);
It looks like you might be simply misreading console.log()
If you try this code:
var obj = {
'1': {
test: 'some data'
}
}
console.log(obj)
It outputs 1: {test: "some data"} to the chrome dev tools console, however it sits below an expandable line that says Object, indicating that the line is in fact a child key of an object. So while the console shows this, the actual object does in fact look like:
{
'1': {
test: 'some data'
}
}
var foo = { "oh" : "yeah" };
var bar = { "no" : "way" };
bar["foo"] = foo;
console.log(bar);

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

In JS, how to declare a value for an object and have all parent keys automatically be created?

myObject = {};
myObject.property1 = "123"
Typing myObject.property1 returns 123
mySecondObject = {};
mySecondObject.property1.value.type.price = "456"
returns TypeError: Cannot set property 'value1' of undefined because all or some parent keys haven't been defined yet, so you have to do something like:
mySecondObject = {};
mySecondObject.property1 = {};
mySecondObject.property1.value = {};
mySecondObject.property1.value.type = {};
mySecondObject.property1.value.type.price = "456"
Is there a method in JS that allows you to just declare an object with as many keys as you want and automatically creates all the parent keys? I couldn't find anything in Underscore.
There's no (standard) function for doing this.
An alternate initialiser is this:
var mySecondObject = { property1: { value: { type: { price : "456" } } } };

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