0

I'm trying to style a button with a loop through the object's keys and values. Values are working but keys are not.

let btn = document.querySelector('.button');
let obj = {color: 'red'}
Object.keys(obj).map(f=>btn.style.f = obj[f])

So, finally it would render like this btn.style.color = 'red'

but btn.style.f, f is not taking but if replace the f with color then it's working.

Any help.

Pranab
  • 305
  • 3
  • 13

1 Answers1

2

You should access btn.style's attribute like this as the attribute is dynamic,

Object.keys(obj).forEach(f=>btn.style[f] = obj[f])

As mentioned in the above link,

You can access object properties by dot notation or by bracket notation.

var x = {'test': 'hi'};
alert(x.test); // alerts hi
alert(x['test']); // alerts hi

When you have a dynamic value, you have to use the latter:

var property = 'test';
alert(x.property); // looks for x.property, undefined if it doesn't exist
alert(x[property]); // looks for x['test'], alerts hi

So what you actually want is:

alert(data[bsID][0].time);

Besides as @charlietfl mentioned, you should use Object.keys(obj).forEach() instead of .map().

Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30