Reputation: 685
here is the function
function createData(_id){
var _temp = '20C';
var _battery = '60%';
var _data = { _id:{temp:_temp,battery:_battery} };
console.log(_data);
}
createData('Thermometer1');
Result :
[
_id:{temp:'20C',
battery:'60%'
}
]
Expected Result:
[
Thermometer1:{temp:'20C',
battery:'60%'
}
]
ignore the text below :v
it looks like your post is mostly code; please add more detail,
i don't know what to write so here is a guitar tab
0 - 3 - 5
0 - 3 - 6 - 5
0 - 3 - 5 - 3 - 0
Upvotes: 0
Views: 87
Reputation: 28
You can use object[attribute]
syntax to refer to a property of an object.
// Example:
let attr = 'candy';
let obj = {};
obj['attr'] = 'cone';
console.log(obj); // { attr: 'cane' }
obj[attr] = 'cane';
console.log(obj); // { attr: 'cone', candy: 'cane' }
// Your Solution:
function createData(_id) {
var _temp = "20C";
var _battery = "60%";
var _data = {};
_data[_id] = {
temp: _temp,
battery: _battery,
};
console.log(_data);
}
createData("Thermometer1"); // { Thermometer1: { temp: '20C', battery: '60%' } }
Upvotes: 0
Reputation: 155
Brackets around _id:
function createData(_id){
var _temp = '20C';
var _battery = '60%';
var _data = { [_id]:{temp:_temp,battery:_battery} };
console.log(_data);
}
createData('Thermometer1');
Edit: You can use a string to define a property of an object anywhere:
let obj = { ['prop']: 42 }
console.log(obj.prop)
console.log(obj['prop'])
Upvotes: 1