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.
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
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
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])
}
Using Object.values:
const data = {
"EUR_BND": 1.603476,
"TEST_BND": 3.4,
"TEST2_BND": 5.6
}
console.log(Object.values(data))
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
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
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
}
Related
Trying to get both key and value using the following script
jsonData = {"jurisdiction":"SCPB - LON","firstName":"David Dynamic"}
var keys = Object.keys(jsonData).map(function(keys, values) {
logInfo(jsonData[keys], jsonData[values]);
});
returns just the values:
2022-08-30 18:29:49 David Dynamic undefined
2022-08-30 18:29:49 SCPB - LON undefined
How can I get both? the js engine is spiderMonkey 1.8
Object.keys(jsonData).forEach(function(key) {
logInfo(key, jsonData[key]);
});
Object.keys documentation
Or as suggested by Kondrak Linkowski:
Object.entries(jsonData).forEach(([key, value]) => logInfo(key, value))
You likely want to use Object.entries to get the keys and values of the object.
If you want to do it with Object.keys, as in your example, you can modify it like this: (logging the key, and the value at this key)
const jsonData = {
foo: 'bar',
fizz: 'fuzz',
}
const logInfo = console.log
var keys = Object.keys(jsonData).map(function(key) {
logInfo(key, jsonData[key]);
});
I have an array object where there are key value pairs. I am trying to get the keys in that array using a loop but I am getting only 0. What is the problem with my code.
var strj = '{"name":"John","age":"30","cars":
[ {"type":"car", "year":"1998"},
{"type":"van", "year":"1995"}]}';
var myobj = JSON.parse(strj)
var care = myobj.cars.filter(c => c.type=='car');
Value of care
0:{type: "car", year: "1998"}
length:1
__proto__:Array(0)
Loop
for (var key in care){
if(care.hasOwnProperty(key)){
console.log(key)
}
}
care is a array type so you cannot do for (var key in care). You need to do for (var key in care[0]). This is because for (var key in care) will look for the key value in care and since it is a array it will always take 0 as a value in key(as you have only one object in array and its index is 0). That is why you got 0 in console.log.
var care =[{type: "car", year: "1998"}];
for (var key in care[0]){
if(care[0].hasOwnProperty(key)){
console.log(key)
}
}
care.forEach( ( singleCar ) => {
for ( var key in singleCar ){
console.log(key);
if( care.hasOwnProperty( key ) ){
console.log(key);
}
}
})
forEach will give you all the objects one by one. so you can check them.
As others have solved the issue, might i make a suggestion - Object.keys () gives an array of the keys for a given object. Since you are getting your filtered object and simply want its keys - the following will achieve that. Note that this is only using the code after you have filtered the original and have gained the "care" object.
As an aside, note that object.values() will give you an array of the values in a given object and object.entries() will give you arrays of the key / value pairing.
var care = {type: "car", year: "1998"};
var keys = Object.keys(care)
console.log(keys) // gives ["type","year"]
filter() method returns a Array of matches.
var care = myobj.cars.filter(c => c.type=='car'); // So, this returns an array.
care.forEach(element => {
console.log(Object.keys(element)); //Prints keys of each element
});
Well actually there is no problem in your code at all. But you just misunderstood the use of javascript filter. Javascript filter() creates new array that's why you are getting 0 as key. If you want to get only one matching element then find() is what you should use.
var strj = '{"name":"John","age":"30","cars":[{"type":"car", "year":"1998"},{"type":"van", "year":"1995"}]}';
var myobj = JSON.parse(strj)
var care = myobj.cars.filter(c => c.type == 'car'); // returns array
var care = myobj.cars.find(c => c.type == 'car'); // returns first matching object
var care = myobj.cars.findIndex(c => c.type == 'car'); // returns first matching index
Javascript filter() method => Read Here
Javascript find() => Read Here
Javascript findIndex() method => Read Here
I have incoming json objects. What i want to do is to filter the JSON based on its key. For example I have three incoming json objects.
Sending message: {"deviceId":"test","temperature":11,"latitude":50,"longitude":19,"time":1,"id":398}
Sending message: {"deviceId":"temp","temperature":11,"latitude":50,"longitude":19,"time":1,"id":399}
Sending message: {"deviceId":"temp","temperature":11,"latitude":50,"longitude":19,"time":1,"id":400}
Sending message: {"deviceId":"test","temperature":11,"latitude":50,"longitude":19,"time":1,"id":01}
Sending message: {"deviceId":"temp","temperature":11,"latitude":50,"longitude":19,"time":1,"id":402}
I want only those json objects where deviceid is test and not temp. I am trying to filter the JSON. How can i do this?
I'll write you an example
say you have list of
let obj = {
"deviceId":"test",
"temperature":11,
"latitude":50,
"longitude":19,
"time":1,
"id":398
}
Then you can selecte deviceId by obj['deviceId']
for (let index in listOfObj){
let curObj = listOfObj[index];
if(curObj['deviceId'] === 'test'){
//Do whatever you want with the object
}
}
This is a basic example which describes how you can check whether the deviceId is 'test' or 'temp' and based on that you can run a loop on the object keys and apply whatever logic you want to apply on it.
Hope this helps.
document.addEventListener("DOMContentLoaded",function(e){
var obj = {
"deviceId":"test",
"temperature":11,
"latitude":50,
"longitude":19,
"time":1,
"id":398
}
if(obj["deviceId"]==="test"){
Object.keys(obj).forEach(function(e){
alert(e+" "+obj[e]);
})
}
})
I suggest you to use Lodash library.
var messages = [{msg1}, {msg2}];
var filteredMessages = _.filter(messages, {deviceId: "test"});
// filteredMessages is an Array of messages with deviceId equals to `test`
Assuming your objects are in an array, you can achieve this using the native Javascript Array#filter method,
var arr = [
{"deviceId":"test","temperature":11,"latitude":50,"longitude":19,"time":1,"id":398},
{"deviceId":"temp","temperature":11,"latitude":50,"longitude":19,"time":1,"id":399},
{"deviceId":"temp","temperature":11,"latitude":50,"longitude":19,"time":1,"id":400},
{"deviceId":"test","temperature":11,"latitude":50,"longitude":19,"time":1,"id":01},
{"deviceId":"temp","temperature":11,"latitude":50,"longitude":19,"time":1,"id":402}
];
var results = arr.filter(function(obj) {
// Return true to keep the element
return obj.deviceId === "test";
});
console.log(results);
In my application I am getting a json result from the controller, which I want to turn to array of arrays in the frontend, so I can work with the google charts api.
Currently I am using a $.parseJSON(result) on the string I am getting, so in the end i get this in the console :
And what i'd like to get is :
Here is the initial json string, which i get before the parseJSON part :
[{"rolename":"some role","perc":45.5},{"rolename":"another role","perc":36.4},{"rolename":"role three","perc":9.1},{"rolename":"role four","perc":9.1}]
Any tips on how can i achieve that?
ES6 ( quite new cool stuff ):
var json=[{"rolename":"some role","perc":45.5},{"rolename":"another role","perc":36.4},{"rolename":"role three","perc":9.1},{"rolename":"role four","perc":9.1}];
var answer=json.map(el=>Object.values(el));
Working: http://jsbin.com/pejucoriqu/edit?console
ES5 ( compatible with a lot browsers):
var answer=json.map(function(el){
var arr=[];
for(var key in el){
arr.push(el[key]);
}
return arr;
});
Youve got an array of objects, And you want an array of arrays. So take each element and map it with the values of the object.
You can use map to change objects to arrays and also Object.keys and map to return only object values.
var data = [{"rolename":"some role","perc":45.5},{"rolename":"another role","perc":36.4},{"rolename":"role three","perc":9.1},{"rolename":"role four","perc":9.1}]
var result = data.map(function(e) {
return Object.keys(e).map(function(k) {
return e[k]
})
})
console.log(result)
Or with ES6 you can use arrow functions like this
var result = data.map(e => Object.keys(e).map(k => e[k]))
My requirement is to store key-value pairs in a data structure and fetch or delete the pairs when necessary using keys in JavaScript.
How can I do it in JavaScript as one does it in Java?
I have seen an answer creating an instance of hash map like:
var hash={};
Now Ie can add values in it like:
hash={ "January":"1","Feb":"2" }
Can I insert values dynamically using keys and fetch them and also get the size of the hash map?
You can use the built-in Map object.
var myMap = new Map();
var keyObj = {};
myMap.set(keyObj, "value");
myMap.get(keyObj);
for (var [key, value] of myMap) {
console.log(key + " = " + value);
}
More information here : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Map
Yes, that's an associative array (var hash = new Object();)
//You can add in these ways:
hash.January='1';
hash['Feb']='2';
//For length:
console.log(Object.keys(hash).length)
//To fetch by key:
console.log(hash['Feb']) // '2'
//To fetch all:
for(var key in hash){
console.log('key is :' + key + ' and value is : '+ hash[key])
}
hash["dynamic"] = 5 will insert something. Object.keys(hash).length will get the size.
Please see this guide on JavaScript Objects:
http://www.w3schools.com/js/js_objects.asp
JavaScript objects can be accessed in a number of ways. Let's take this object as an example:
var person = {
first_name: "John",
last_name: "Smith",
age: 39
};
If you wished to access the first_name you could do:
person.first_name;
Or
person['first_name'];
These would both retrieve the value.
You may also set the value in similar fashion:
person.first_name = "Michael";
Now, if you were referring to creating an iterator using a keys() method like in Java then you can't do that exactly, but you can do something similar.
You can iterate over the object however in a similar manner that you would iterate over an array:
for (var property in object) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
A newer built-in is also available where you can use Object.keys(person) to get an array of the objects keys. Read more here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
I suggest using Google a little more. There are plenty of resources out there for this type of question. You would find the answer more quickly than someone would respond on here.
elegant and simple javascript hashmap code
var hashMap=function(){
this.hashDict={};//dictionary
this.size=0;
this.debug=true;
return this;
}
now to insert :
hashMap.prototype.put=function(_key,_value){
if (!this.hashDict.hasOwnProperty(_key)) {
this.hashDict[_key] = _value;
++this.size;
}
else if(this.debug)
throw 'duplicate keys not allowed. key : '+_key;
}
you can also get the size using and perform all other manipulations
only you have to do is create the object of class hash map like :
hashmap n = new hashMap();
n.put('key','value');
n.get('key');
n.size; // gives size