var contact = { varWorkExperiences: [{ Experience: "aaa" },Experience: "bbb"}] };
I have a structure like this. I can use push method like this:
contact.varWorkExperiences.push({ Experience: "ccc"});
but I want to do this paramaticly
I cant do this:
var x = "Experience";
contact.varWorkExperiences.push({ x: "ccc"});
How can I solve this? I have to use push method in function but I can't pass attribute as a parameter.
var x = "Experience";
var obj = {};
obj[x] = "ccc";
contact.varWorkExperiences.push(obj);
Related
I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:
var key = "happyCount";
myArray.push( { key : someValueArray } );
but when I try to examine my array of objects for every object the key is "key" instead of the value of the variable key. Is there any way to set the value of the key from a variable?
Fiddle for better explanation:
http://jsfiddle.net/Fr6eY/3/
You need to make the object first, then use [] to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2021:
Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.
const yourKeyVariable = "happyCount";
const someValueArray= [...];
const obj = {
[yourKeyVariable]: someValueArray,
}
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";
var person = {[key]:"John"};
console.log(person); // should print Object { name="John"}
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also
supports computed property names. That allows you to put an expression
in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
Use this.
var key = 'a'
var val = 'b'
console.log({[key]:val})
//a:'b'
In ES6 We can write objects like this
const key= "Name";
const values = "RJK"
const obj = {
[key]: values,
}
In TypeScript, it should look something like this
let title ="Current User";
type User = {
[key:string | number | symbol]: any
};
let myVar: User = {};
myVar[ title ] = "App Developer";
console.log(myVar)// Prints: { Current User:"App Developer"}
let key = "name";
let name= "john";
const obj ={
id:01
}
obj[key] = name;
console.log(obj); // output will {id:01,name:"john}
Use square brackets shown it will set as key
The Reality
The problem in JS is simply that:
{ x: 2 }
is THE SAME as:
{ "x": 2 }
(even if you have x a variable defined!)
Solution
Add square brackets [] around the identifier of the key:
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
(Nowadays the keyword var is not much used, so please use instead const or let)
tldr;
I have latsArr and LongsArr filled from firebase automatically.
I want to populate latsAndLongsArray in viewDidLoad function. How can I do that?
var latsArr = [1111.0,2222.0,333.0]
var longsArr = [444.0,555.0,666.0]
var latsAndLongs = [[111.0,444.0],[222.0,555.0],[333.0,666.0]]
Use the zip(_:_:) and map(_:) methods combined to get the expected result:
let latsAndLongs = zip(latsArr, longsArr).map { [$0.0, $0.1] }
var latsAndLongs = zip(latsArr, longsArr).map({[$0.0, $0.1]})
One option (which uses tuples instead of arrays) is to use zip.
var latsArr = [1111.0,2222.0,333.0]
var longsArr = [444.0,555.0,666.0]
var latsAndLongs = zip(latsArr, longsArr)
// latsAndLongs == [(1111.0, 444.0), (2222.0, 555.0), (333.0, 666.0)]
I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:
var key = "happyCount";
myArray.push( { key : someValueArray } );
but when I try to examine my array of objects for every object the key is "key" instead of the value of the variable key. Is there any way to set the value of the key from a variable?
Fiddle for better explanation:
http://jsfiddle.net/Fr6eY/3/
You need to make the object first, then use [] to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2021:
Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.
const yourKeyVariable = "happyCount";
const someValueArray= [...];
const obj = {
[yourKeyVariable]: someValueArray,
}
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";
var person = {[key]:"John"};
console.log(person); // should print Object { name="John"}
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also
supports computed property names. That allows you to put an expression
in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
Use this.
var key = 'a'
var val = 'b'
console.log({[key]:val})
//a:'b'
In ES6 We can write objects like this
const key= "Name";
const values = "RJK"
const obj = {
[key]: values,
}
In TypeScript, it should look something like this
let title ="Current User";
type User = {
[key:string | number | symbol]: any
};
let myVar: User = {};
myVar[ title ] = "App Developer";
console.log(myVar)// Prints: { Current User:"App Developer"}
let key = "name";
let name= "john";
const obj ={
id:01
}
obj[key] = name;
console.log(obj); // output will {id:01,name:"john}
Use square brackets shown it will set as key
The Reality
The problem in JS is simply that:
{ x: 2 }
is THE SAME as:
{ "x": 2 }
(even if you have x a variable defined!)
Solution
Add square brackets [] around the identifier of the key:
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
(Nowadays the keyword var is not much used, so please use instead const or let)
tldr;
I need to get the inner object value in localStorage.i.e object inside the object.
var filter = {
filterWord: null,
userId: null
}
filter.filterWord = listCAO.sortName;
filter.userId = listCAO.currentUser;
listCAO.filterBreadcumText.push(filter);
localStorage.setItem('entityBreadCumText', listCAO.filterBreadcumText);
LocalStorage only holds String pairs: 'string1'='string2'
So when you do localStorage.getItem('string1') it returns 'string2'.
If you want to store a Javascript Object, you need to convert it into a string first. JSON works best for that.
var myObj = [{'name': 'Paul', 'age': 22}, {'name': 'Steve', 'age': 68}];
myStr = JSON.stringify(myObj);
localStorage.setItem('myData', myStr);
Same when you read the data from localStorage
var myStr = localStorage.getItem('myData');
var myObj = JSON.parse(myStr);
var myName = myObj[0].name;
Or in one step
var myName = JSON.parse(localStorage.getItem('myData'))[0].name;
This may be another solution.
You can use it this way.
let obj = JSON.parse(localStorage.getItem('your_settings_name'));
let lobj: YourObject = <YourObject>obj;
If the data is stored as nested objects instead of an array as c14l 's answer, the syntax changes a little bit.
Let's store nested object first:
var myNestedObject = {"token": "Bearer", "profile": {"name":"Mustafa","expires_at":1678013824}};
myNestedStr = JSON.stringify(myNestedObject);
localStorage.setItem('myNestedData', myNestedStr);
Now let's see how to get the "name" from the nested object:
var nestedStr = localStorage.getItem('myNestedData');
var nestedObj = JSON.parse(nestedStr);
var nestedProfile = nestedObj.profile;
var nestedName = nestedProfile.name;
Or we can get "name" with a single line also:
var nestedNameWithOneLine = JSON.parse(localStorage.getItem('myNestedData')).profile.name;
I have string something like this "12,13" and I want to convert into array like this [12,13] in controller. I used split function it does not work.
$scope.mySplit = function(string, nb) {
var array = string.split(',');
return array[nb];
}
$scope.isChecked = function(id,matches) {
var isChecked = false;
var arr= [];
arr = $scope.mySplit(matches,0);
console.log(arr);
};
One problem might be that you did not define arr to be a variable as such: var arr = $scope.mySplit(matches,0);. Or another variable. Unless you declared it globally somewhere else.
Look at this jsfiddle that works: https://jsfiddle.net/wapp4u5g/