TechnoCorner TechnoCorner - 5 months ago 10
Javascript Question

Object get the value by a key

I'm kinda stuck with an issue. This is the response for my AJAX call.

var test = [
"analytics.feature": "false"
"demo": "true"
"analytics.demo": "false"

Now I want to check if analytics.demo is enabled or disabled.

Can I use _.find?

_.find(test, {analytics.demo});
//returns error

I just want to do this

if(analytics.demo) {
//Do something

How do I do that? Can someone help?

Instead of iterating objects and comparing, can I use underscorejs/jQuery to get the exact value for a key?

const options = Object.assign(...test)
console.log(options) // { "analytics.feature": "false", demo: "true", "analytics.demo": "false" }
if (options['analytics.demo'] === 'true') {
  // ...

(Note that this uses ES6. For ES5 use var options = Object.assign.apply(object, test) instead, and you also need to polyfill Object.assign.)

This uses Object.assign() with the spread operator to merge the objects into one, then get the "analytics.demo" option from the new single object. It has to be accessed using bracket notation because the key has a dot in. It is compared to the string true because "false" (string) is true but false (boolean) is false.

There is more information on SO about flattening arrays and converting strings to booleans.

PS is there any way you can get the Ajax call to use proper booleans instead of strings? It would be easier to work with.