how to use var as key of object into react project [duplicate] - reactjs

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;

Related

Mutating the object in the setState [duplicate]

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;

Retrieve the Object values and assign it to Another one Object in ReactJS

I have to retrieve an object and assign it to another one. But in the new object, always the last item only stored.
I tried object.entries keys method but nothing worked.
code : https://codesandbox.io/s/k3p7j07x8o
let subject = {};
const obj = { a: 5, b: 4, c: 9 };
for (const [key, value] of Object.entries(obj)) {
console.log(`${key} ${value}`);
//console.log(subject); // Here itself it's printing the last element
subject.value = key;
subject.text = value;
console.log(subject.value + subject.text); // This showing the correct element
console.log(subject); // This one showing the last elements
}
You can use this syntax:
let subject = Object.assign({}, obj}
console.log(subject)
or
let subject = {};
Object.assign(subject, obj);
console.log(subject)

Get struct properties from string - swift

I declared a struct with 4 properties ( informationA, informationB, informationC, informationD ).
Also I've declared an array like this (The array includes some names of the my_struct properties as "strings" :
let keys = ["informationA", "informationB", "informationC"]
Now I'd like a for-loop to go through the "keys"-array and print out the struct property values for the current string ("informationA", "informationB", "informationC").
struct my_struct {
var informationA = "test"
var informationB = "test...test"
var informationC = "test...test"
var informationD = "test...test..."
}
func getInformation() {
let keys = ["informationA", "informationB", "informationC"]
for i in keys {
print(my_struct.i) // ERROR: Type 'my_struct' has no member 'i'
// should print ---> "test", "test...test", "test...test"
}
}
Using the code from above I'm getting this error ERROR: Type 'my_struct' has no member 'i'.
Is there a way to avoid this message and achieve the result I'd like to get?
What you are looking for is reflection:
struct MyStruct {
var informationA = "test"
var informationB = "test...test"
var informationC = "test...test"
var informationD = "test...test..."
}
func getInformation() {
let my_struct = MyStruct()
let keys = ["informationA", "informationB", "informationC"]
let m = Mirror(reflecting: my_struct)
let properties = Array(m.children)
for k in keys {
if let prop = properties.first(where: { $0.label == k }) {
print(prop.value)
}
}
}

Why can't I use the array's append() in Swift?

I'm getting a: Cannot invoke 'append' with an argument list of type '([Book])' It works find if I use the += but I don't understand why append() won't work.
struct Book
{
var title:String
var pageCount:Int
}
class Library
{
var onShelfBooks:[Book] = []
var onLoanBooks:[Book] = []
var books:[Book]
{
get
{
return onShelfBooks + onLoanBooks
}
set(newBook)
{
onShelfBooks.append(newBook)
}
}
}
struct Book
{
var title:String
var pageCount:Int
}
class Library
{
var onShelfBooks:[Book] = []
var onLoanBooks:[Book] = []
var books:[Book]
{
get
{
return onShelfBooks + onLoanBooks
}
set(newBook)
{
onShelfBooks.append(newBook[0])
}
}
}
var myLibrary = Library()
var newBook = Book(title: "Swift Development with Cocoa", pageCount: 453)
myLibrary.books = [newBook]
myLibrary.books
Append only allows you to add one object at a time while += allows you to combine an array of objects with another object. When you call append on the setter you are trying to add an array of book objects, or [Book] instead of just a single book object.
If you would like to add [newBook] with append, you can use : of
1- onShelfBooks.append(contentsOf: newBook)
"contentOf" is type of Sequence.
otherwise use of:
2- onShelfBooks += newBook

How to add the new value by replacing the old value in ArrayCollection in actionScript3?

public var streamList:ArrayCollection=new ArrayCollection();
//am getting the streamList dynamically like WebUser7,WebUser11.....
private function streamSynch(event:SyncEvent):void
{
if(streamList.length>0){
//(streamList)here in streamList am getting the all values(old)
streamList.removeAll();
}
var results:Object = event.target.data;
for( var item:String in results ) {
streamArray.push(item);
}
streams = new ArrayCollection(streamArray);
streamList=streams; //(streamList)here in streamList am getting the all values(new) like Webuser9,WebUser2,WebUser11......
From my Example i need to add the Webuser9,WebUser2,WebUser11,WebUser7
}
I need to compare the old and new,and then replace the old and add the new...
You can do this by using ArrayCollection method setItemAt(item:Object, index:int):Object. You just have to know an index of element you want to replace.
EDIT:
There is usage example
function arrayCollectionExample () : void {
// create instance of array collection
var arrayCollection : ArrayCollection = new ArrayCollection();
// create some object that we will add to collection
var obj1 : Object = { name : "Object1" };
var obj2 : Object = { name : "Object2" };
var obj3 : Object = { name : "Object3" };
// add those objects to collection
arrayCollection.addItem( obj1 );
arrayCollection.addItem( obj2 );
arrayCollection.addItem( obj3 );
// and now let's create a new object that we will want add instead of obj2
var obj4 : Object = { name : "Object4" };
// lets say that we don't remember that index of obj2 in a collection is "1". We have to get from collection
var obj2Index : int = arrayCollection.getItemIndex( obj2 );
trace( obj2Index ) // 1
// now when we know index we can replace obj2 with obj4
arrayCollection.setItemAt( obj4, obj2Index );
// now when we have replaced values we can see that item at index "1" property "name" is "Object4"
trace( arrayCollection.getItemAt( obj2Index )["name"] ) // "Object4"
}

Resources