Object
JavaScript: Basic Object Variable
Categories:
Object size
var size = Object.keys(myObj).length;
Assign the object variable key from another variable
Assisn key-value after object init
const key = "someKey";
const value = "someValue";
const obj = {};
// set the object key using the variable
obj[key] = value;
console.log(obj); // { someKey: "someValue" }
Assisn key-value when object init
The key of the object is set using the computed property names syntax ([key])
. This allows you to use the value of the key variable as the key of the object.
const key = "someKey";
const value = "someValue";
const obj = {
[key]: value
};
console.log(obj); // { someKey: "someValue" }
Import javascript object key and assign it to the new variable
let person = {
name: 'KJ',
age: 17,
jobTitle: 'No Job',
};
// KJ, 17
const { name, age } = person;
Import javascript object key and rename it to the different variable name
let person = {
name: 'KJ',
age: 17,
jobTitle: 'No Job',
};
// KJ, 17
const {
name: kj_name,
age: kj_age
} = person;