Array<object> in typescript - arrays

I wanna add an object to an array but I don't know how to declare a variable with the return type is Array<object>.
My example:
var obj = {
'Prop name': 'Prop value'
};
document.body.innerHTML = typeof obj; // output: object
var arr: Array<object>; // error message: Cannot find name 'object'
arr.push(obj);
I've tried again with:
var obj: Object = {
'Prop name': 'Prop value'
};
document.body.innerHTML = typeof obj; // output: object
var arr: Array<Object>;
arr.push(obj); // error message: Cannot read property 'push' of undefined
How can I fix the issue?

The first error is because it's Object (title case) not object (lower case)
The second error is because you've typed the variable, but not actually assigned an instance. Try:
var arr: Array<Object> = [];
arr.push(obj);

You miss initialization of arr array:
var obj: Object = {
'Prop name': 'Prop value'
};
document.body.innerHTML = typeof obj; // output: object
var arr: Array<Object> = []; // MODIFIED
arr.push(obj);

You should use Object or any instead:
var arr: Array<any>;

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;

ReactJs - TypeError: Cannot assign to read only property 'name' of object '#<Object>'

I have an array of objects:
var subcategories = [{name:'gloves', tag:'wool'}, {name:'boots', tag: 'leather'}]
All I want to do is to find the index of the object to change a name or a tag. I use this function:
function setSubcat(val, index, lang){
var newArr = []
var obj = {
'name': val
}
subcategories.map((val, i)=>{
if(index === i){
var newObj = Object.assign(val, obj)
newArr.push(newObj)
}
newArr.push(val)
})
setSubcategories(newArr)
}
The error happens at var newObj = Object.assign(val, obj)
I thought the error means I can't mutate the state directly and so I have to make a copy. I thought that mapping through subcategories and push it into a local newArr means I made a copy of the array. But it wasn't working when I wanted to change a value of object in it so I used Object.assign which I thought would deep copy the particular object from the array, but it's not working either.
What am I missing here?
As pointed in comments:
the code you posted does not show how you created object with unmodifiable property
you can create a new object and not use Object.assign to get rid of the error
use map function in more idiomatic way
interface TaggedItem {
name: string,
tag: string
}
var subcategories = [{name:'gloves', tag:'wool'}, {name:'boots', tag: 'leather'}];
function setSubcat(val: string, index: number, _lang: any){
var obj: Partial<TaggedItem> = {
'name': val
}
var newArr: TaggedItem[] = subcategories.map((val, i)=>{
if(index === i){
return {
...val,
...obj
}
} else {
return {...val};
// or return val; if you don't need a full copy
}
})
console.log(newArr);
}
setSubcat('newName', 0, undefined);
Playground link

how to use var as key of object into react project [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;

How can I map an object in order to change it?

I need to map an object
obj={a:'',b:firstname,c:'',d:lastname}
while mapping if an element of an object does contain : '', i will return to to null so the result will be like that :
obj={a:null,b:firstname,c:null,d:lastname}.
How can I do that?
You can use Object.keys to get an array of all the property names in the object, and then use reduce to build up a new object where all properties with value '' get the value null instead.
const obj = { a: "", b: "foo", c: "", d: "bar" };
const result = Object.keys(obj).reduce((acc, key) => {
acc[key] = obj[key] === '' ? null : obj[key];
return acc;
}, {});
console.log(result);
You can do this by using for in
var obj = {a:'',b:'firstname',c:'',d:'lastname'}
for(var key in obj){
if(obj[key] === ""){
obj[key] = null
}
}
console.log(obj)

Initializing array of objects - Angular

I have an array of objects and when I try to access to it, I get an error saying:
TypeError: Cannot set property 'ID' of undefined
My code is the following:
export class Carimplements OnInit {
pieces: Piece[] = [];
test(pos){
this.pieces[pos].ID = "test";
}
}
being Piece an object
export class Piece{
ID: string;
doors: string;
}
I call to test(pos) from the HTML with a valid position.
I guess that I am trying to access to the position X of an array that has not been initialized. How could I do it? Is it possible to create a constructor?
Correct syntax for defining array types in TypeScript is this:
pieces: Piece[] = [];
The error is a runtime error. When you run your app you have an empty array pieces (but the variable still initialized with []) but you call test(whatever) which tries to access an array element whatever that doesn't exist.
You can do for example this:
pieces: Piece[] = [{
ID: '1',
doors: 'foo'
}];
and then test this method with test(0).
How about this?
export class Carimplements OnInit {
pieces: Piece[] = [];
test(pos){
this.pieces[pos] = {ID: "test"};
}
}
let pieces: Piece[] = [];
//initialize object before assigning value
test(pos){
this.pieces[pos] = new Piece();
this.pieces[pos].ID = "test";
}
You can try the following method
test(pos){
if(pos < this.pieces.length)
this.pieces[pos].ID = "test";
else
// throw error
}

Resources