How to Add Dynamically Named Properties to JavaScript Object

Is it possible to add dynamically named properties to JavaScript object?

Yes.

var data = {

'PropertyA': 1,

'PropertyB': 2,

'PropertyC': 3

};

data["PropertyD"] = 4;

// dialog box with 4 in it

alert(data.PropertyD);

alert(data["PropertyD"]);

How to create an object with dynamic property names

In your code fruits.props[i] = 'Juice'; would try to set the 0th index value of props property where the property is undefined and causing the error.

Use bracket notation for assigning object property using a string.

var fruits = {};

var props = ['orange', 'apple', 'banana'];

for (var i = 0; i < props.length; i++) {

fruits[props[i]] = 'Juice';

//----^^^^^^^^^^-----

}

console.log(fruits);

How do I dynamically assign properties to an object in TypeScript?

Index types

It is possible to denote obj as any, but that defeats the whole purpose of using typescript. obj = {} implies obj is an Object. Marking it as any makes no sense. To accomplish the desired consistency an interface could be defined as follows.

interface LooseObject {
[key: string]: any
}

var obj: LooseObject = {};

OR to make it compact:

var obj: {[k: string]: any} = {};

LooseObject can accept fields with any string as key and any type as value.

obj.prop = "value";
obj.prop2 = 88;

The real elegance of this solution is that you can include typesafe fields in the interface.

interface MyType {
typesafeProp1?: number,
requiredProp1: string,
[key: string]: any
}

var obj: MyType ;
obj = { requiredProp1: "foo"}; // valid
obj = {} // error. 'requiredProp1' is missing
obj.typesafeProp1 = "bar" // error. typesafeProp1 should be a number

obj.prop = "value";
obj.prop2 = 88;

Record<Keys,Type> utility type

Update (August 2020): @transang brought this up in comments

Record<Keys,Type> is a Utility type in typescript. It is a much cleaner alternative for key-value pairs where property-names are not known.
It's worth noting that Record<Keys,Type> is a named alias to {[k: Keys]: Type} where Keys and Type are generics.
IMO, this makes it worth mentioning here

For comparison,

var obj: {[k: string]: any} = {};

becomes

var obj: Record<string,any> = {}

MyType can now be defined by extending Record type

interface MyType extends Record<string,any> {
typesafeProp1?: number,
requiredProp1: string,
}

While this answers the Original question, the answer here by @GreeneCreations might give another perspective on how to approach the problem.

Dynamically access object property using variable

There are two ways to access properties of an object:

  • Dot notation: something.bar
  • Bracket notation: something['bar']

The value between the brackets can be any expression. Therefore, if the property name is stored in a variable, you have to use bracket notation:

var something = {
bar: 'foo'
};
var foo = 'bar';

// both x = something[foo] and something[foo] = x work as expected
console.log(something[foo]);
console.log(something.bar)

How to add a property to an object's property that is dynamically named

a.b is equivalent to a["b"] so when you're doing aaa.bbb you're not doing anything related to the bbb variable.

aaa[bbb].description this is correct to set a property on aaa[bbb], however, aaa[bbb] needs to be an object.

An easier way do to this would be:

var aaa = {};
var bbb = 2;
var ccc = 5;
aaa[bbb] = {description: differentObject[ccc].description};

How do I create a dynamic key to be added to a JavaScript object variable

Square brackets:

jsObj['key' + i] = 'example' + 1;

In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0", "5", "207", and so on, are all treated specially in that their existence determines the value of length. And, on top of that, the value of length can be set to remove such properties. Setting the length of an array to 0 effectively removes all properties whose names look like whole numbers.

OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ] operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.

Thus, the way the [ ] operator works in a for loop iterating through an array:

for (var i = 0; i < myArray.length; ++i) {
var value = myArray[i]; // property access
// ...
}

is really no different from the way [ ] works when accessing a property whose name is some computed string:

var value = jsObj["key" + i];

The [ ] operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

When setting property values using [ ], the story is the same except for the special behavior around maintaining the length property. If you set a property with a numeric key on an array instance:

myArray[200] = 5;

then (assuming that "200" is the biggest numeric property name) the length property will be updated to 201 as a side-effect of the property assignment. If the same thing is done to a plain object, however:

myObj[200] = 5;

there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5 in otherwise the exact same way.

One might think that because that length behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:

var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;

var objJSON = JSON.stringify(obj);

the value of "objJSON" will be a string containing just ["hello world"]; the "something" property will be lost.

ES2015:

If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:

var key = 'DYNAMIC_KEY',
obj = {
[key]: 'ES6!'
};

console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }

Create object from array of objects by dynamic properties

The simplest way is just to write a loop. Let's start with just JavaScript and then we'll come back to types:

const result = {};
for (const entry of myArray) {
for (const key in entry) { // or: of Object.keys(entry)
const values = result[key] = result[key] ?? [];
values.push(entry[key]);
}
}

Live Example:

const myArray = [
{
"width": 10,
"height": 20
},
{
"width": 20,
"height": 40
},
{
"width": 30,
"height": 60
}
];

const result = {};
for (const entry of myArray) {
for (const key in entry) { // or: of Object.keys(entry)
const values = result[key] = result[key] ?? [];
values.push(entry[key]);
}
}
console.log(result);
.as-console-wrapper {
max-height: 100% !important;
}


Related Topics



Leave a reply



Submit