Ruhan Konduru
Ruhan Konduru

Reputation: 1

Get the value from objects in JavaScript

I was inspecting some code through Firebug's debugger. The value I found is wrapped in this.executions. So when I print the value of temp

var temp = this.executions;
console.log(temp);

I am getting output as

[Object { context="1461223497558",  value1="TEST1",  value2="TEST2"}]

I tried using a for...in loop

for(var key in temp) {
  var value = temp[key];
}

Though then I am still getting output like

Object { context="1461223497558",  value1="TEST1",  value2="TEST2"}

I want to extract the values TEST1 and TEST2 of the variables value1 and value2 key. Any idea how to get them?

Upvotes: 0

Views: 55

Answers (3)

Andy
Andy

Reputation: 63587

filter the object values that start with 'TEST' (ES6):

var obj = arr[0];
var out = Object.keys(obj).filter(el => obj[el].substring(0, 4) === 'TEST');

DEMO

Or perhaps a more general function (this time ES5):

function extractValues(obj, str) {
  return Object.keys(obj).filter(function(el) {
    return obj[el].substring(0, str.length) === str;
  });
}

extractValues(obj, 'TEST'); // ['TEST1', 'TEST2']

DEMO

Upvotes: 0

Sebastian Zartner
Sebastian Zartner

Reputation: 20125

Note that your first output

[Object { context="1461223497558",  value1="TEST1",  value2="TEST2"}]

is an array of objects indicated by the square brackets around the object.

Therefore you first need to loop over that array (e.g. by using your for...in loop) and then access the properties of the current object:

for(var key in temp) {
  var object = temp[key];
  console.log(object.value1, object.value2);
}

Upvotes: 0

mimiz
mimiz

Reputation: 2288

Iterate over keys :

var keys  = Object.keys(temp[0]); // As your first temp var is an array
keys.forEach(function(key){
 console.log(key +" : " +temp[key]);
});

Or first iterate on executions :

this.executions.forEach(function(temp){ // loop over executions
    var keys  = Object.keys(temp);
    keys.forEach(function(key){ // loop over keys
     console.log(key +" : " +temp[key]);
    });
});

this will outpout

context : 1461223497558
value1 : TEST1
...

So now you can do what you want with your data

Upvotes: 3

Related Questions