Store object inside object and update - javascript

I am trying to store an array inside and object like this:
var fieldData = {
checkedItem: {
fieldID : “1234”,
SelectedFields : []
}
checkedItem: {
fieldID : “12345”,
SelectedFields : []
}
}
I then want to also replace all selected fields to this object at a later stage.
I am a newbie to this so not sure how it would be done, I have tried everything I can think of!
The later changes to the object will referenced by fieldID.
I have tried stuff like:
fieldData["fieldID"] = selectedFieldSeq;
fieldData[selectedFieldSeq]["SelectedFields"] = $('#Tree').jqxTree('getCheckedItems');
$('#Tree').jqxTree('getCheckedItems');
returns an array of checked items on my tree.

This should do it:
'fieldID = $('#Tree').jqxTree('getCheckedItems');'
'fieldData.SelectedFields = fieldID'

There is a problem with this line :
fieldData[selectedFieldSeq]["SelectedFields"]
fieldData[selectedFieldSeq] is not defined, so it's return undefined
You need to initialize it before using it :
if (!fieldData[selectedFieldSeq]) {
fieldData[selectedFieldSeq] = {
SelectedFields : []
};
}
After, you can assign some value to SelectedFields.
Or did you want to simply do this : fieldData.SelectedFields = ...; ?

Related

getting the key/pair values out of an object that in an object

Objects thats returned:
ref.orderByChild('name').once('value').then(function(snapshot){
var results = snapshot.val();
When i log results the image is what i get, Ive been trying to access the value of 'active' for each of the three objects, phishing, information and techniques.
This is my first JS application sorry if its an easy one but couldn't find an answer else where that worked.
There are two (common) ways to do this: the Firebase way and the regular JavaScript way.
the Firebase way
Since it seems you're returning a list of nodes, I'll start with the Firebase way.
ref.orderByChild('name').once('value').then(function(snapshot){
var actives = {};
snapshot.forEach(function(childSnapshot) {
var result = childSnapshot.val();
var key = result.key;
var active = result.active;
actives[key] = active;
}
console.log(actives);
}
So we're using Firebase's Snapshot.forEach() method here to loop over the child nodes.
the regular JavaScript way
Alternatively you can get the value of the entire snapshot as you already do and use plain old JavaScript to get the result you need. Jatin's answer shows one way to do that, but here's another:
ref.orderByChild('name').once('value').then(function(snapshot){
var results = snapshot.val();
var keys = Object.keys(results); // ["information", "phishing", "techniques"]
var actives = {};
keys.forEach(function(key) {
actives[key] = results[key].active;
});
console.log(actives);
}
So in this case we're using Object.keys() to get the child node names and then loop over that array with JavaScript's Array.forEach().
var snapshot = {
"information" : {
"active" : "y",
"name" : "information"
},
"phishing" : {
"active" : "z",
"name" : "phishing"
},
"techniques" : {
"active" : "x",
"name" : "techniques"
},
};
console.log(snapshot.information.active);
console.log(snapshot.phishing.active);
console.log(snapshot.techniques.active);

Automatically update JavaScript object property when another object's property is set

I have an array of objects, each containing a property named title.
The title property can hold one of two possible string values - "main" or "local". Only a single element in the array can have "main" as its title value at a given time, and the rest of the elements should have their title property set to "local".
For instance, take the following array:
var locations = [
{
title:"main",
place:"UK"
},
{
title:"local",
place:"USA"
},
{
title:"local",
place:"RUSSIA"
}
]
When setting the place:"USA" object's title property to "main", I want place:"UK" object's title property to automatically be set to "local".
How to achieve this with javascript?
One way to do this is set all title values to local, before setting desired object to main.
Another way is to remember which index is currently set to main and revert it to local when main is to be changed.
The following will return a copy of your array with the desired changes:
With ES6/Babel:
// Example:
somePlace = 'USA';
const newLocations = locations.map(l =>
{ ...l, title: l.place === somePlace ? 'main' : 'local' }
);
With Vanilla JS/Lodash:
// Example:
somePlace = 'USA';
var newLocations = _.map(locations, function (l) {
return _.assign({}, l, { title: l.place === somePlace ? 'main' : 'local' });
);
var newMainIndex = 2;
var locations = [
{
title:"main",
place:"UK"
},
{
title:"local",
place:"USA"
},
{
title:"local",
place:"RUSSIA"
}
];
for(var i=0, len=locations.length;i<len;i++){
locations[i].title = i === newMainIndex ? "main" : "local";
}

How to delete a key within an object in local storage with Javascript and/or Jquery?

In local storage I have an object named favourites and it contains this..
"{
"id3333":{
"URL":"somewhere.comm/page1/",
"TITLE":"Page 1 Title",
},
"id4444":{
"URL":"somewhere.comm/page2/",
"TITLE":"Page 2 Title",
}
}"
How can I delete an object based on its ID (id3333 & id4444 for examples)
I have tried the following along with some other voodoo..
localStorage.removeItem('id3333'); // no errors, no removal
localStorage.removeItem('favourites':'id3333'); // SyntaxError: missing ) after argument list
localStorage.removeItem('favourites[id3333]'); // no errors, no removal
localStorage.removeItem('id3333', JSON.stringify('id3333')); // no errors, no removal
Also, I will need to get the key name to delete based on a variable, so like this..
var postID = 'id3333';
localStorage.removeItem(postID);
or
var objectName = 'favourites';
var postID = 'id3333';
localStorage.removeItem(objectName[postID]);
Is it possible to remove a nested item directly or do I need to retrieve the full object and then delete the item and then set the object back to local storage again?
The closest I can get to deleting anything directly so far is..
localStorage.removeItem('favourites');
But that of course removes the entire object.
You have a a single key and you are acting like there are multiple keys
var obj = {
"id3333":{
"URL":"somewhere.comm/page1/",
"TITLE":"Page 1 Title",
},
"id4444":{
"URL":"somewhere.comm/page2/",
"TITLE":"Page 2 Title",
}
};
window.localStorage.favs = JSON.stringify(obj); //store object to local storage
console.log("before : ", window.localStorage.favs); //display it
var favs = JSON.parse(window.localStorage.favs || {}); //read and convert to object
var delKey = "id3333"; //key to remove
if (favs[delKey]) { //check if key exists
delete favs[delKey]; //remove the key from object
}
window.localStorage.favs = JSON.stringify(favs); //save it back
console.log("after : ", window.localStorage.favs); //display object with item removed
With localStorage.removeItem you can only remove top level keys, i.e. keys directly on localStorage.
Because id3333 is on localStorage.favourites you cannot remove it using localStorage.removeItem.
Instead try delete localStorage.favourties['id3333']
Simple, actually: you just delete it. :)
x = {
"id3333":{
"URL":"somewhere.comm/page1/",
"TITLE":"Page 1 Title",
},
"id4444":{
"URL":"somewhere.comm/page2/",
"TITLE":"Page 2 Title",
}
};
console.log(x);
delete x.id3333;
console.log(x);
delete does what you're looking for. You could also do something like delete x.id3333.TITLE if you were so inclined. Note also that delete returns true if successful and false if not.
Suppose you set a nested object in localStorage like that
const dataObj = {
uid: {
name: 'robin',
age: 24,
}
}
window.localStorage.setItem('users', JSON.stringify(dataObj));
Now you want to delete the age property. You can't remove it with removeItem native function since it allows to delete from top level.
So you need to get the data first and delete the property you want and set the data again to localStorage with updated value like that
const existingLocalStorage = JSON.parse(window.localStorage.getItem('users') || {});
if(existingLocalStorage['uid']['age']) { // if throws any error, use lodash get fucntion for getting value
delete existingLocalStorage['uid']['age'];
}
window.localStorage.setItem('users', JSON.stringify(existingLocalStorage));

Add an array to a json object in extjs

I wish to have an attribute called idField in my json object. Now this attribute is either an array if it contains multiple elements or just an object if it contains one element. I wish to create such an attribute from the data in an extjs store. In essence if the store contains just one element I need to insert this idField 'object' in the json object otherwise I need to insert an 'array' called idField in the json object. Please advise as to how to do that.
EDIT:
My store has 2 columns namely 'name' and 'type' in its data. What I wish is that if it contains just one element then my object should look like this:
{
...
idField : {
name : ...
type : ...
}
}
If my store contains 2 rows then my object should look like this :
{
...
idField : [
{
name : ...
type : ...
},
{
name : ...
type : ...
}
]
}
Also I have to INSERT this idField attribute inside the object. There is no currect idField attribute yet in the object.
EDIT 2:
I received this object in the console when I wrote console.log(Ext.getStore("My_store_name").data)
To get the data from the EXT JS store
var data = Ext.getStore("Your_Store_Name").data
In my snippet below I am assuming that you like to get the values from field name called item.
var data = Ext.getStore("Your_Store_Name").data
//imagine your JSON where you need to store is in variable myJSON
if (data.items.length == 1){
myJSON.idField = {type: 'sometype', name: data.item[0]} }
else if (data.item.length > 1)
{ //make an array of JSON
var list = [];
for(var i = 0; i < data.item.length; i++)
{
list.push({type: 'sometype', name: data.item[i]})
}
myJSON.idField = list; //set the array
}

Check case insentively if a value is in an array, and if the case doesn't match, replace it with the new value

I am attempting to replace the values in an array with the correct case sensitivity. This is because I am attempting to correct user inputs. I retrieve the correct casing from a page, and the user will have an array of values, some of which will be incorrect.
Ex:
userValues = ["apple321", "orange_22", "pineApple" , "Cantelope", "grASShopper_9000"];
var value1 = "Apple321";
var value2 = "orange_22";
var value3 = "Cantelope";
var value4 = "GrassHopper_9000";
Then after some function ran through all the values, the result would be:
userValues = ["Apple321", "orange_22", "pineApple" , "Cantelope", "GrassHopper_9000"];
The reason I have value1, value2, etc is because I've already created a loop to run through an object. Just not sure how to compare the resulting values. Here is what I have already however:
// When the user enters data, it's sometimes case insensitive. This normalizes the data.
function NormalizeData(downloaded_data)
{
$.each(downloaded_data, function(website,streams){
$.each(streams, function(stream_name,value){
stream_list[website] // This is the global variable array
value.displayName; // This is the value I need to check case sensitivity, and replace with the new case if different
});
});
}
Here is the requested data structure:
downloaded_data = {
twitch_tv : {
timthetatman : {
Online: "1",
Website: "twitch_tv",
displayName: "TimTheTatman"
}
}
}
streamlist = {
twitch_tv : {
["timthetatman"]
}
hitbox_tv: {
[]
}
}
I figured it out. Since I am using an array for the values I want to change, and not an object, it's actually much simpler than I thought. I ran a loop on every value, and if the lowercase of both values matched, but the non-lowercase values didn't, I replaced it in the array, using the numerical key as a reference.
function NormalizeData(downloaded_data)
{
$.each(downloaded_data, function(website,streams){
$.each(streams, function(stream_name,value){
$.each(stream_list[website], function(arrKey,arrVal){
if(arrVal.toLowerCase() == stream_name.toLowerCase() && stream_list[website][arrKey] !== value.displayName)
stream_list[website][arrKey] = value.displayName;
});
});
});
}
Here it is, simplified, if the array is called Array1 and the value Value1:
var Array1 = ["apple"];
var Value1 = ["Apple"];
$.each(Array1, function(arrKey,arrVal){
if(arrVal.toLowerCase() == Value1.toLowerCase() && arrVal !== Value1)
Array1[arrKey] = Value1;
});

Categories

Resources