Accessing a JSON object based on one key-value - javascript

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);

Related

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.
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
}

How to extend an array with new array without declaration

I am working on project where I need to maintain an array from json data returned from API, json can have tree, I have following code which is working fine but I wan to remove if conditions before assigning values to array elements
// data contains json
let newArray = []
for(let d in data){
for(let x in data[d]){
if(typeof(newArray[d]) === 'undefined'){
newArray[d] = []
}
if(typeof(newArray[d][data[d][x]['id']]) === 'undefined'){
newArray[d][data[d][x]['id']] = []
}
newArray[d][data[d][x]['id']]['price'] = data[d][x]['price']
newArray[d][data[d][x]['id']]['discount'] = data[d][x]['discount']
}
}
In above code I have to check the array first and declare it as array if its not otherwise it returns undefined error, is there any way to get rid of there conditions and extend array as per requirement ?
You can you new ES6 spread operator like this
newAraay[d] = [...newArray,...Array(data[d][x]['id']),[...Array('price',data[d][x]['price'])]]
Like here in this snippet I am directly doing abc[1][3][4] = "new value" without explicitly initialising them
let abc = [];
abc[1]= [...abc,...Array(3),[...Array(4),'new inserted value']]
console.log(abc);
newArray[d] = newArray[d] || []
You can understand this operation in this post
Or use Lodash Library
https://lodash.com/docs/4.17.11#set

How do I update my array with my object's value? [duplicate]

This question already has answers here:
How do I update specific key value of the local storage array?
(4 answers)
How to store and update a localStorage key object which has properties of different data types?
(1 answer)
Closed 4 years ago.
myObj is storing the input coming from the user which is pushed to arr which is store in localStorage as a 'data' key. On submit, I want the new values to be added to arr and not overwrite it (in the else part). The following code works but overwrites the old data:
var myObj = {
field1: fname.value,
field2: lname.value,
field3: birth.value,
field4: salary.value,
field5: String(selectedGender),
field6: String(choicesOfHobby),
field7: color.value,
field8: String(choicesCountry),
field9: textArea.value
}
const arr = new Array()
if (window.localStorage.length == 0) {
const arr = JSON.stringify(myObj);
window.localStorage.setItem('data', arr);
} else {
const arr = JSON.stringify(myObj);
window.localStorage.setItem('data', arr);
}
One thing to note is that JSON.stringify returns a string, not an array -- and, conveniently, localStorage stores key/value pairs where the value is a string, so this all works as it's supposed to.
To update the value in localStorage, you could first retrieve it, then modify it however you like, and then store it again. Since you're working with javascript objects, you'll need to use JSON.parse and JSON.stringify to convert back and forth between objects (to work with) and strings (to store).
This pattern looks like:
let retrievedString = localStorage.getItem('data');
let retrievedObject = JSON.parse(retrievedString); // convert string to obj
let oldColor = retrievedObject.field7; // we don't actually use oldColor
let newColor = "#666666";
retrievedObject.field7 = newColor; //change existing property
retrievedObject.field99 = "99"; // add new property
let modifiedString = JSON.stringify(retrievedObject); // ready to store new version
localStorage.setItem('data', modifiedString);
I added more to the code sample to clarify the kinds of things you can do with your retrieved object before converting back to a string and finally replacing the old version in storage.
Your mistakes:
arr, despite its name, isn't an array.
you never recover the saved data
Check the code below to see my take on the problem: (before trying it, you should erase your localStorage)
var myObj = {
field1: fname.value,
field2: lname.value,
field3: birth.value,
field4: salary.value,
field5: String(selectedGender),
field6: String(choicesOfHobby),
field7: color.value,
field8: String(choicesCountry),
field9: textArea.value
}
const array = window.localStorage.data || []; // get your saved array, or create a new one
array.push(myObj); // Add the current item to the array
window.localStorage.setItem('data', JSON.stringify(array)); // save it again
Any further question please just ask
You need to use something like this:
let data = localStorage.getItem('data');
let dataObj = JSON.parse(data);
dataObj[fieldKey] = fieldObj;
localStorage.setItem('data', JSON.stringify(dataObj));
Firstly read localstorage documents how to use it: https://developer.mozilla.org/tr/docs/Web/API/Window/localStorage
You have to push data array to localstorage and push your objects to your data array after getting data array from localstorage. Finally don't forget to set your data array to localstorage again. Your localstorage part code should be like below:
var data = JSON.parse(window.localStorage.getItem("data"));
if(data === null){
data = [];
}
data.push(myObj);
window.localStorage.setItem("data",JSON.stringfy(data));
You just need to use this:
arrInStorage = localStorage.getItem('data') || [];
arr = JSON.parse(arrInStorage);
arr.push(myObj);
localStorage.setItem('data', JSON.stringify(arr));
instead of your if / else statement.

How to convert a JSON object to array of arrays

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]))

Is there a way to create hashmap in javascript and manipulate it like adding and deleting values

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

Categories

Resources