Deleting previous items in object when iterating over data Javascript - javascript

Outside my scope I have:
var imageData = {};
Then I iterate over my data with jQuery .each like such:
$.each(imgData, function(imagesI) {
imageData = imagesI.QuoteImage;
console.log(imagesI);
})
So when I console log imagesI I get back so many objects (it's different each time) for example my console log looks like;
Object {theImage: "select_q26", Info: "Some info", InfoMeaning: "Info Meaning"}
However, whenever I console.log my object outside which is imageData I only ever get the last object I get from iterating over my data.
Is there anyway to add each object I get back to the variable above without overriding the last one I added?
Thanks!

You could use an array and push the values to that
var imageData = [];
$.each(imgData, function(imagesI) {
imageData.push( imagesI.QuoteImage );
});

Related

chrome.storage.local.get an object and iterating through obj keys

I'm having trouble using the chrome.storage.local.get feature. I have all working, except I don't understand how to handle the .get function.
I want to copy an object by clicking a button, from one chrome tab to another one. I have a loop to get my Object keys, and I can save it successfuly in chrome local storage by:
chrome.storage.local.set({
'copiedObj': obj
});
but, when trying to use the .get function, I can't specify the key number I want. I need the key number because the keys and their values changes every time because i'm copying data from different pages.
$('#targetInfo').click(function(){
console.log('context 2 received');
var storage = chrome.storage.local.get('copiedObj', function (items) {
console.log(items);
});
});
this gets me the full object keys and values, but when trying to change it to get the first key (changing the console.log inside the script to items[0], I get an undefined error message in the console.
I want it to iterate through all the keys, and assign key to a variable, value to a variable and execute a function. For each key by it's time. I've written a detailed explanation inside the code:
//Get the DOM input field
var specific_name = document.getElementById('new_specific_name');
var specific_value = document.getElementById('new_specific_value');
//Start loop, from 0 to the last object keys
for (i=0;i<items.length;i++) {
//Set specific_name value to the first key inside the object
specific_name.value = XXX[i];
//Set specific_value value to the matching key value inside the object
specific_value.value = ZZZ[i];
//Execute this function
add_new_specific();
}
(minimal solution, pending clarification) As mentioned before,
var storage = chrome.storage.local.get('copiedObj', function (items) {
console.log(items);
});
should be
var storage = chrome.storage.local.get('copiedObj', function (result) {
console.log(result.items);
console.log(result.items[0]); // if items is an array...
});
To loop through an object, see https://stackoverflow.com/a/18202926/1587329. You need to do this all inside the anonymous function in .get.

Reading an object's value in JavaScript

I want to get the features from my layer. So I'm requesting WMSGetFeatureInfo method after a successful request for GetFeatureInfo on my layer.
The returned object is structured like this:
I can read values like BEVDICHTE with var bevdichte = features.BEVDICHTE and so on.
But when I want to get the value of the_geom with var the_geom = features.the_geom it returns an object. Yes it is nested so this is intended but my question is how to get the value ol.geom.MultiPoint
from the_geom?
EDIT:
Unfortunately var target = features.the_geom['actualEventTarget_']; will just return another 'actualEventTarget_' object. This is because the the_geom object is nested into infinity. I attached another screenshot to describe my problem. There are many more nested eventTargets following. Yet I was not able to get the property ol.geom.MultiPolygon.
To access a nested array, just use brackets: '[ ]'
var nestedArray = [[1,2], [3,4]];
var nestedArrayValue = nestedArray[0][0];
// --> returns 1
With your example:
var target = features.the_geom['actualEventTarget_']
By the way, from the looks of it var the_geom = features.the_geom doesn't seem like an array. It has keys, mapped to a value, are you sure this is an array, not an object?

How can I copy the contents of a Javascript object to an empty one?

I have a Javascript object (JSON returned from a database) for use in an Angular site:
[{'widget_id':'1','widget_name':'Blue Widget','widget_description':'A nice blue widget','widget_discount':'20'},{'widget_id':'2','widget_name':'Red Widget','widget_description':'A fantastic red widget','widget_discount':'0'}]
I want to process this information before I use it in my view - say I want to alter the discount or perform some other operations. Therefore I want to make a new object, iterate through my JSON, and write certain values from the JSON object to the new, blank object.
For now I've just been trying to test copying one value from the old array to a new one, in my Angular controller:
WidgetSvc.fetchWidgets().success(function(response){
var rawWidgets = response
var widgetsOutput = {}
for (var i in rawWidgets){
widgetsOutput[i].widget_id = rawWidgets[i].widget_id
}
But this throws a cannot set property 'widget_id' of undefined error. I suspect I'm not initializing the new object properly.
What am I doing wrong?
You just forgot to set you nested object before setting property :
var rawWidgets = [{'widget_id':'1','widget_name':'Blue Widget','widget_description':'A nice blue widget','widget_discount':'20'},{'widget_id':'2','widget_name':'Red Widget','widget_description':'A fantastic red widget','widget_discount':'0'}];
var widgetsOutput = {}
for (var i in rawWidgets){
widgetsOutput[i] = {}
widgetsOutput[i].widget_id = rawWidgets[i].widget_id
}
console.log(widgetsOutput)
JSON != Javascript Object. You can JSON.parse() to make your JSON into a proper Javascript object:
WidgetSvc.fetchWidgets().success(function(response){
var data = JSON.parse(response);
// now you can do
data[0].widget_discount = 10;
}

How do I access this javascript object?

{"profit_center" :
{"branches":
[
{"branch": {"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3310","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3311","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"0","site_survey":"1","branch_number":"3312","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3313","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"0","site_survey":"1","branch_number":"3314","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3315","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}}
],
"profit_center_name":"Alabama"}}
I tried accessing it in ajax through this,
data.profit_center //data here is the ajax variable e.g. function(data)
or through this data["profit_center"]
but no luck
How do I access this javascript object properly. ?
By the way that code above is from console.log(data)
EDIT:
Result from console.log(data.profit_center) and console.log(data["profit_center"]) is undefined
You can put your datain a variable like
var json = data
and you can access profit_center like
alert(json.profit_center);
alert(json.profit_center.profit_center_name); //Alabama
for(var i =0 ;i<json.profit_center.branches.length;i++){
alert(json.profit_center.branches[i]);
}
Okay I have found out why it is undefined, It is a json object so I need to parse it before i can access it like a javascript object.
var json = JSON.parse(data);
Then that's it.
First parse your data if you've not already done so.
You can access, for example, each branch_number like so:
var branches = data.profit_center.branches;
for (var i = 0, l = branches.length; i < l; i++) {
console.log(branches[i].branch.branch_number);
}
In summary, profit_center is an object and branches is an array of objects. Each element in the array contains a branch object that contains a number of keys. Loop over the branches array and for each element access the branch object inside using the key names to get the values.
The profit center name can be found by accessing the profit_center_name key on the profit_center object:
console.log(data.profit_center.profit_center_name); // Alabama
You could even use the new functional array methods to interrogate the data and pull out only those branches you need. Here I use filter to pull those objects where the purchase_order is equal to 2. Note that the numeric values in your JSON are strings, not integers.
var purchaseOrder2 = branches.filter(function (el) {
return el.branch.purchase_order === '2';
});
DEMO for the three examples

Javascript pushing objects into array changes entire array

I'm using a specific game making framework but I think the question applies to javascript
I was trying to make a narration script so the player can see "The orc hits you." at the bottom of his screen. I wanted to show the last 4 messages at one time and possibly allow the player to look back to see 30-50 messages in a log if they want. To do this I set up and object and an array to push the objects into.
So I set up some variables like this initially...
servermessage: {"color1":"yellow", "color2":"white", "message1":"", "message2":""},
servermessagelist: new Array(),
and when I use this command (below) multiple times with different data called by an event by manipulating servermessage.color1 ... .message1 etc...
servermessagelist.push(servermessage)
it overwrites the entire array with copies of that data... any idea why or what I can do about it.
So if I push color1 "RED" and message1 "Rover".. the data is correct then if I push
color1"yellow" and message1 "Bus" the data is two copies of .color1:"yellow" .message1:"Bus"
When you push servermessage into servermessagelist you're really (more or less) pushing a reference to that object. So any changes made to servermessage are reflected everywhere you have a reference to it. It sounds like what you want to do is push a clone of the object into the list.
Declare a function as follows:
function cloneMessage(servermessage) {
var clone ={};
for( var key in servermessage ){
if(servermessage.hasOwnProperty(key)) //ensure not adding inherited props
clone[key]=servermessage[key];
}
return clone;
}
Then everytime you want to push a message into the list do:
servermessagelist.push( cloneMessage(servermessage) );
When you add the object to the array, it's only a reference to the object that is added. The object is not copied by adding it to the array. So, when you later change the object and add it to the array again, you just have an array with several references to the same object.
Create a new object for each addition to the array:
servermessage = {"color1":"yellow", "color2":"white", "message1":"", "message2":""};
servermessagelist.push(servermessage);
servermessage = {"color1":"green", "color2":"red", "message1":"", "message2":"nice work"};
servermessagelist.push(servermessage);
There are two ways to use deep copy the object before pushing it into the array.
1. create new object by object method and then push it.
servermessagelist = [];
servermessagelist.push(Object.assign({}, servermessage));
Create an new reference of object by JSON stringigy method and push it with parse method.
servermessagelist = [];
servermessagelist.push(JSON.parse(JSON.stringify(servermessage));
This method is useful for nested objects.
servermessagelist: new Array() empties the array every time it's executed. Only execute that code once when you originally initialize the array.
I also had same issue. I had bit complex object that I was pushing in to the array. What I did; I Convert JSON object as String using JSON.stringify() and push in to the Array.
When it is returning from the array I just convert that String to JSON object using JSON.parse().
This is working fine for me though it is bit far more round solution.
Post here If you guys having alternative options
I do not know why a JSON way of doing this has not been suggested yet.
You can first stringify the object and then parse it again to get a copy of the object.
let uniqueArr = [];
let referencesArr = [];
let obj = {a: 1, b:2};
uniqueArr.push(JSON.parse(JSON.stringify(obj)));
referencesArr.push(obj);
obj.a = 3;
obj.c = 5;
uniqueArr.push(JSON.parse(JSON.stringify(obj)));
referencesArr.push(obj);
//You can see the differences in the console logs
console.log(uniqueArr);
console.log(referencesArr);
This solution also work on the object containing nested keys.
Before pushing, stringify the obj by
JSON.stringify(obj)
And when you are using, parse by
JSON.parse(obj);
As mentioned multiple times above, the easiest way of doing this would be making it a string and converting it back to JSON Object.
this.<JSONObjectArray>.push(JSON.parse(JSON.stringify(<JSONObject>)));
Works like a charm.

Categories

Resources