0

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

2 Answers 2

1

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']) 
Sign up to request clarification or add additional context in comments.

Comments

0

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%' } }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.