Clore Nora
Clore Nora

Reputation: 137

Get the value of an Element in an array

i'm trying to get the value of a Object in my array. Basically when i'm doing

var firsts = response.data;
console.log(firsts)

I have something like that

{
 "EUR_BND": 1.603476
}

But the name of the object is changing every time, so i can't do

response.data.EUR_BND

I wondered if there was a way to directly get the value of the only object, without having to go through its name.

Upvotes: 0

Views: 85

Answers (7)

Ismail Diari
Ismail Diari

Reputation: 519

The best way for me, is to get the list of keys and then you can do whatever you want with it,
Maybe your need can evolve in the future, so it is recommended that you start by getting your keys and do the logic you wish

var keys = Object.keys(data);
if(keys && keys.length>0)
{
var firstValue = data[keys[0]];
//other staff
}

Upvotes: 0

Rafat Rashid
Rafat Rashid

Reputation: 312

This is how you may access "EUR_BND" key within response.data or firsts object.

var firsts = response.data;
var keys = Object.keys(firsts);
console.log(firsts[keys[0]]);

I would suggest having a look at Object.keys method here

Upvotes: 0

Rahul juneja - DevOps
Rahul juneja - DevOps

Reputation: 790

Object.values gives you a list of all values of a object keys, you can use it

<script>
data = {
 "EUR_BND": 1.603476
};
value_a = Object.values(data)[0];
console.log(value_a); #1.603476
</script>

This way you don't need to use the object key to get the value

Upvotes: 0

Shantun Parmar
Shantun Parmar

Reputation: 429

Try best way to get all key and value in loop

const data = {
 "EUR_BND": 1.603476,
 "TEST_BND": 3.4,
 "TEST2_BND": 5.6
}
    var key;

for (key in data) {
    console.log(key+' '+data[key])
} 

Upvotes: 2

Jule Wolf
Jule Wolf

Reputation: 221

You could retrieve the keys with

Object.keys(obj)

like it is stated in the docs and then access the value like you normally would:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Upvotes: 2

Aadil Mehraj
Aadil Mehraj

Reputation: 2614

Using Object.values:

const data = {
 "EUR_BND": 1.603476,
 "TEST_BND": 3.4,
 "TEST2_BND": 5.6
}

console.log(Object.values(data))

Upvotes: 1

Guruparan Giritharan
Guruparan Giritharan

Reputation: 16364

You can use the object.values

Object.values(response.data)

Which would return an array of the values in the object

Object.values(response.data)[0] would return the value if you have one

Upvotes: 2

Related Questions