This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed last month.
How would I access a variable if I have its name stored in a string?
let test1 = 6;
let test2 = 4;
function findVar(index) {
let result = "test" + index;
console.log(result);
}
findVar(1);
findVar(2);
Running this just prints 'test1' and 'test2' as strings, how can I access their values?
// default / window context
var test1 = 6;
var test2 = 4;
// sub / object context
var context2 = {
subProp1 : 10
}
// find var using key of object /context
// because 'everything' is an Object...
// we can reference properties / attributes using the key
function findVar( prefix, index, context ) {
return context[ prefix + index ];
}
console.log( findVar( 'test', 1, this ) ); // outputs 6
console.log( findVar( 'test', 2, this ) ); // outputs 4
console.log( findVar( 'subProp', 1, context2 ) ); // outputs 10
Related
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 2 years ago.
I have an array of names:
var namesArray = [Matthew, Mark, Luke, John]
And I want to convert each to a variable of the same or similar name, ie:
var MatthewVar = 1;
var MarkVar = 2;
var LukeVar = 3;
var JohnVar = 4;
But I need to do this dynamically (let's say the array has many more names in it).
This is what I had, but it doesn't like the var name:
for(var i = 0; i<namesArray.length; i++){
var (namesArray[i] + 'Var') = namesArray[0].indexOf(namesArray[i]) + 1;
}
Thoughts?
const namesArray = ['Matthew', 'Mark', 'Luke', 'John'];
const namesObject = namesArray.reduce((namesObject, name, index) => {
namesObject[name] = index + 1;
return namesObject;
}, {});
console.log(namesObject); // { Matthew: 1, Mark: 2, Luke: 3, John: 4 }
console.log(namesObject.Matthew); // 1
console.log(namesObject['Matthew']); // 1
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 4 years ago.
I have the following array
const lastThreeYearsArr = [currYear, currYear-1, currYear-2 ]
I need to define an object as:
var obj = {lastThreeYearsArr[0]: 0, lastThreeYearsArr[1]: 0, lastThreeYearsArr[2]: 0};
But using the array as key doesn't seem to work in javascript. Is there a way to access the array value and put it as key in the object.
You could create a new object by iterating the keys and use Object.assign with computed property names.
var lastThreeYearsArr = ['currYear', 'currYear-1', 'currYear-2'],
object = lastThreeYearsArr.reduce((o, k) => Object.assign(o, { [k]: 0 }), {});
console.log(object);
You can specify the properties using bracket notation instead of the object literal notation. For example:
const x = [2011, 2012, 2013]
let y = {}
y[x[0]] = 0
use a simple forEach and assign new properties with bracket notation :
const currYear = (new Date()).getFullYear();
const lty = [currYear, currYear - 1, currYear - 2]
let result = {};
lty.forEach((e, i) => {
result[e] = 0
})
console.log(result)
Enclose each key with brackets [] which are used for computed property names
You can use Object.assign as already suggested but if IE compatibility is required a basic loop will do too.
var currYear = 2018;
var lastThreeYearsArr = [currYear, currYear - 1, currYear - 2]
var obj = {};
for (var i = 0; i < lastThreeYearsArr.length; i++) {
obj[lastThreeYearsArr[i]] = 0;
}
console.log(obj);
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 4 years ago.
Suppose I have an object
var obj = {
subObj : {
value : 1
}
};
Is there any way to get obj.subObj.value using a complex property-name string that goes to sub objects?
Example (that doesn't work)
var attr = "subObj.value";
return obj[attr];
No you can't.
You can split and loop over every attr.
var obj = {
subObj : {
value : 1
}
};
var attr = "subObj.value";
var result = obj;
attr.split('.').forEach((c) => result = result[c]);
console.log(result);
Or you can use reduce:
var obj = {
subObj : {
value : 1
}
};
var attr = "subObj.value";
var result = attr.split('.').reduce((a, c) => a[c], obj);
console.log(result);
There is no notation to do this in JavaScript but you could use something like this:
var obj = {
subObj : {
value : 1
}
};
var attr = "subObj.value";
var result = attr.split(".").reduce((a, c) => a[c], obj);
console.log(result)
EDIT: SOLVED See final solution below
EDIT: The value names are not the same
object 1
var obj1 = {
val1a : 4,
val2a : 3 ,
val3a : 7
}
object 2 with arrays
var obj2 = {
val1b : [one, two, three],
val2b : [oneA, twoA, threeA],
val3b : [oneB]
}
I am trying to do is the following
if(obj1.val1a === obj2.val1b.length){
// code
}
but I do not want it to be so specific. Is there a way to loop over each object and return the values of obj2 that do not match obj1
SOLUTION with underScore
function checkData(obj1, obj2) {
result = []
var keys_obj1 = Object.keys( obj1)
var keys_obj2 = Object.keys( obj2)
_.each(keys_obj1, function(num, i){
if(obj1[keys_obj1[i]].length !== obj2[keys_obj2[i]]) {
result.push(keys_obj1[i]);
}
})
return result;
}
The best way to do this is if both objects have the same name (for a given pair), then using The For/In Loop iterate over one of them and return the value of both, and then compare.
Remade the fiddle using Object.keys to make an array of keys for both objects, now it works even when the keys aren't the same (following the object index)
var obj1 = {
val1a : 4,
val2a : 3 ,
val3a : 7
}
var obj2 = {
val1b : ['one', 'two', 'three'],
val2b : ['oneA', 'twoA', 'threeA'],
val3b : ['oneB']
}
var keys_obj1 = Object.keys( obj1 )
var keys_obj2 = Object.keys( obj2 )
for (i = 0; i < keys_obj1.length; i++) {
console.log(keys_obj1[i]+'-'+obj1[keys_obj1[i]])
console.log(keys_obj2[i]+'-'+obj2[keys_obj2[i]].length);
if(obj1[keys_obj1[i]] === obj2[keys_obj2[i]].length) {
//match
}
}
console output :
"val1a-4"
"val1b-3"
"val2a-3"
"val2b-3"
"val3a-7"
"val3b-1"
If your model is not the definitive one, you could use an array of object like :
var object = [
{table : [one, two, three], length : 3},
{table : [one, two, three], length : 4},
... ];
and compare values using :
object[i].table.length === object[i].length
It's a little bit different from your model
but i hope it may helps.
Quite long-winded, but the only way I could think to do it:
// for each object you are going to...
function pullData(obj) {
var out = {};
var token;
// grab the keys
var keys = Object.keys(obj).map(function (el) {
// token is the character at the end of the key
// the key that is returned is the key without the token
token = el.slice(-1)
return el.slice(0, 4);
});
// for each key, add it to the output object
for (var i = 0, l = keys.length; i < l; i++) {
out[keys[i]] = obj[keys[i] + token]
}
// return an object containing the data and the token
return {data: out, token: token};
}
// take both the output from both objects being parsed
function isNotMatch(obj1, obj2) {
var out = [];
// loop over the first object using the now identical keys
for (var p in obj1.data) {
// check the values and lengths
// if they're not the same push the key and the token as a string
// to the output array
if (obj1.data[p] !== obj2.data[p].length) {
out.push(p + obj2.token);
}
}
// return the array of non-matches
return out;
}
isNotMatch(pullData(obj1), pullData(obj2));
DEMO
UPDATED:
Maybe something like this. You would have to make sure the property names are the same:
var obj1 = {
val1a : 4,
val2a : 3 ,
val3a : 7
};
var obj2 = {
val1a : ['one', 'two', 'three'],
val2a : ['oneA', 'twoA', 'threeA'],
val3a : ['oneB']
};
for(var name in obj1) {
if(obj1[name] === obj2[name].length) {
alert("match");
}
}
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I'm try to parse a object from response to web service, that has the following structure:
{ "idRonda":"1",
"puntos":{
"p1":{"id":1,"descripcion":"punto uno","tag":"0497e1b13e0280"},
"p2":{"id":2,"descripcion":"punto dos","tag":"0498e9b13e0280"},
"p4":{"id":4,"descripcion":"punto cuatro","tag":"04419092432f80"},
"p5":{"id":5,"descripcion":"punto cinco","tag":"0462f812b82a80"},
"p3":{"id":3,"descripcion":"punto tres","tag":"046cfd92432f80"}
}
}
So, I try to iterate over the "array" puntos, then I do the following:
//data has the response from web service
var json = JSON.parse(data);
var puntos = json.puntos; //until here it's ok
When I print the value and type of puntos :
console.log( " Puntos Object : "+ puntos );
console.log( " TypeOf : "+ Ember.typeOf(puntos) );
Output:
Puntos Object : [object Object]
TypeOf : string
My attempt:
for (var k in puntos)
{
// I thought that k must be "p1", "p2"..., but I'm wrong
if (puntos.hasOwnProperty(k))
{
var values = puntos[k];
var id = values['id'];
}
}
If I print the k value I get(I don't know what mean it):
key: 0
key: 1
.
.
.
key: 13
key: 14
key: fmt
key: w
key: loc
key: camelize
key: decamelize
key: dasherize
key: underscore
key: classify
key: capitalize
key: htmlSafe
Now how iterate over the puntos object to get id, descripcion and tag values?
UPDATE:
var puntos = json.puntos;
var db = window.sqlitePlugin.openDatabase("Rondas", "1.0", "Dev", -1);
db.transaction(function(tx)
{
tx.executeSql("SELECT * from Punto;", [], function(tx, res)
{
if( res.rows.length === 0)
{
for (var k in puntos)
{
if (puntos.hasOwnProperty(k))
{
var id = puntos[k].id;
var descripcion = puntos[k].descripcion;
var tag = puntos[k].tag;
console.log( "KEY: "+k+" ,ID: "+id + " ,DESCRIPCIĆN: "+descripcion+" ,TAG: "+tag );
}
}
}
}
}
The code above fail becase the object puntos lost the scope because it inside of a callback then then only solution is ensure the object context.
SOLUTION
db.transaction(function(tx)
{
//ensure the object context.
var points = puntos;
tx.executeSql("SELECT * from Punto;", [], function(tx, res)
{
if( res.rows.length === 0)
{
for (var k in points)
{
...
}
}
}
}
Using a for loop like this
for(key in puntos)
{
var id = puntos[key].id;
var descripcion= puntos[key].descripcion;
var tag = puntos[key].tag;
}