How to get every value in Json by key in Javascript [duplicate] - javascript

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 5 years ago.
I am making a rest call to a webservice. In its body it contains a Json file with 18 pairs key, value.
I which to make separate operations on each element so i would like to:
get the different key elements. so i would have an array of the key elements.
With each of those elements, get the corresponding value by dot walking.
Here is what I have:
var obj = JSON.parse(request.body.dataString);
var myKeys = Object.keys(obj)
for (var i = 0; i < myKeys.length; i++){
var iter = myKeys[i];
gs.log(obj.iter);
}
But the gs.log returns undefined.
I have tried to make this:
gs.log(obj.myId);
and it returns the value i want, since myId is one of the elements in keys.
How can i use the elements of my keys array to get the corresponding values?
I have confirmed that hte var myKeys has all the elements of keys and the var obj contains all the json file.

You need to use the [] syntax.
var iter = myKeys[i];
gs.log(obj[iter]);
Plain obj.iter tries to get a property called literally iter. If you want to get a property based on the string value of the variable iter, you need to access the object using obj[iter].

Related

How to append value in an existing object without change the first object with javascript? [duplicate]

This question already has answers here:
Clone Object without reference javascript [duplicate]
(4 answers)
Closed 5 years ago.
My javascript code like this :
var data= {product_id: 4, name: 'nike'}
console.log(data)
var dataNew = data
dataNew.id = 1
console.log(dataNew)
Demo is like this : https://jsfiddle.net/oscar11/69dw8dv1/
I append value in the object like that
The result of console.log(data) and console.log(dataNew) is there exist id
I want var data is no id
So there is only var dataNew that has id
How can I do it?
In JavaScript, object references are assigned, instead of the object values, unless the object is of primitive data types.
That's why dataNew and data refers to the same object when you do this:
var dataNew = data;
To prevent this, you need to create a copy of data like this:
var dataNew = Object.assign({}, data);
Now, the changes in dataNew won't affect data.

calling an object using variable [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 5 years ago.
I have several javascript sliders on a page and I want to be able to enable or disable each by using a variable.
For example, I have a slider:
var slider1 = new Slider('#sitSlider', {
formatter: function(value) {
return value;} });
and I enable/disable it with this:
slider1.disable();
I would like to be able to do something like this to turn off several switches:
for(x=0;x<20;x++){
var tmpStr = "slider"+x;
tmpStr.disable();
}
I did some searching and tried this without success:
this[tmpStr].disable();
How do I go about using a variable to call an object? Thanks.
Edit: Here's the slider component I'm using: Bootstrap Slider
Create an array:
var sliders = [];
Push your objects onto that array:
sliders.push(new Slider(...));
Then in your loop you can access the array elements:
for(x = 0; x < sliders.length; x++){
sliders[x].disable; // side note: missing parentheses here?
}
Any time you're trying to use an incrementing number as part of a variable name, you're probably looking for an array or collection of some kind.
No. You cannot do that. Variable name shouldn't be given like that.
The easiest you can do create an array and push your sliders. And you can loop the array and access the sliders.
var sldsr =[];
...
sldsr.push(slider1);
...
sldsr.push(slider2);
for(x=0;x<sldsr.length;x++){
sldsr[x].disable();
}

Accessing an object from a JSON array of objects yields "Undefined" [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I'm using a Blockspring API that returns a JSON array of objects (read in from a Google Sheet). However, whenever I try to access an object from the array, an "undefined" value is returned. I have attached the code and the console log below. Does anyone have any ideas why?
blockspring.runParsed("query-public-google-spreadsheet", { "query": "SELECT A, B, C", "url":
"https://docs.google.com/spreadsheets/d/1ZYvcYf_41aghdXRSpg25TKW4Qj9p1Lpz92b1xG-9R1Q/edit?usp=sharing"},
{ "api_key": "br_50064_1fe91fe1478ef990dc8b5e9b4041c2c476670306" }, function(res){
var obj=res.params;
console.log(obj);
var temp=obj[0];
console.log(temp);
}
You need to use obj.data[0] to access the first element of an array.
Looking at your output in the console, it seems you are missing the data property of obj.
Object obj doesn't have a property with name 0 so it returns undefined.
I would need to play around with it myself but I can tell that the problem is just how you are accessing the info.
When you try to grab the data with var temp=obj[0] you are treating object like an array when is it not. I would recommend trying to grab the data using this:
//get the actual array
JSONArray theArray = obj.getJSONArray("data"); //I believe it is stored in an array called data... could be that the obj is just fine
// now get the first element:
JSONObject firstItem = theArray.getJSONObject(0);
// and so on
String name = firstItem.getString("Name"); // A
You most likely can grab it using var temp = obj.data[0];

How to sort a bi-dimensional javascript array? [duplicate]

This question already has answers here:
Sort an array based on another array of integers
(7 answers)
Closed 8 years ago.
var global=[];
var value=[50,1,4,29];
var title=["d","b","c","a"];
title.forEach(function(title,i) {
global[title]=value[i];
})
I would like to sort the global array by value but I can't figure out how.
I precise I can't use any library jquery,underscore...
thanks !
the goal is to know what object has the less value.
a,b,c,d have values 50,1,4,29
I can sort values but how to know what's the name associated to this value ?
You're not using global[] correctly as an array in your loop. You can't reference array items with [title], you can either push to the array global.push(value[i]) or use global[i] = value[i]. If you use either of these methods you can just call 'global.sort()' to sort the array which will give you [1, 29, 4, 50]. If you want to use the array as multidimensional, you need to change your loop to something like this:
title.forEach(function(title,i) {
global[i] = {};
global[i][title]=value[i];
})
which will give you [Object { d=50}, Object { b=1}, Object { c=4}, Object { a=29}]
If you want to sort this you could use sort which takes a function in which you can write your custom sorter but I don't think you can use this as all your keys are different. If all your keys were the same, say 'value' ,i.e [Object { value=50}, Object { value=1}, Object { value=4}, Object { value=29}] , you could do:
global.sort(function(a,b) {
return parseInt(a.value, 10) - parseInt(b.value, 10);
});
but this can't be applied to your array since all the keys are different.

Every character in an array being recognized with ".hasOwnProperty(i)" in javascript as true with Google Apps Script

This is the array:
{"C8_235550":
{"listing":"aut,C8_235550_220144650654"},
"C8_231252":
{"listing":"aut,C8_231252_220144650654"}}
It was fetched with a GET request from a Firebase database using Google Apps Script.
var optList = {"method" : "get"};
var rsltList = UrlFetchApp.fetch("https://dbName.firebaseio.com/KeyName/.json", optList );
var varUrList = rsltList.getContentText();
Notice the .getContentText() method.
I'm assuming that the array is now just a string of characters? I don't know.
When I loop over the returned data, every single character is getting pushed, and the JavaScript code will not find key/value pairs.
This is the FOR LOOP:
dataObj = The Array Shown At Top of Post;
var val = dataObj;
var out = [];
var someObject = val[0];
for (var i in someObject) {
if (someObject.hasOwnProperty(i)) {
out.push(someObject[i]);
};
};
The output from the for loop looks like this:
{,",C,8,_,2,3,5,5,5,0,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,5,5,5,0,_,2,2,0,1,4,4,6,5,0,6,5,4,",},,,",C,8,_,2,3,1,2,5,2,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,1,2,5,2,_,2,2,0,1,4,4,6,5,0,6,5,4,",},}
I'm wondering if the array got converted to a string, and is no longer recognized as an array, but just a string of characters. But I don't know enough about this to know what is going on. How do I get the value out for the key named listing?
Is this now just a string rather than an array? Do I need to convert it back to something else? JSON? I've tried using different JavaScript array methods on the array, and nothing seems to return what it should if the data was an array.
here is a way to get the elements out of your json string
as stated in the other answers, you should make it an obect again and get its keys and values.
function demo(){
var string='{"C8_235550":{"listing":"aut,C8_235550_220144650654"},"C8_231252":{"listing":"aut,C8_231252_220144650654"}}';
var ob = JSON.parse(string);
for(var propertyName in ob) {
Logger.log('first level key = '+propertyName);
Logger.log('fisrt level values = '+JSON.stringify(ob[propertyName]));
for(var subPropertyName in ob[propertyName]){
Logger.log('second level values = '+ob[propertyName][subPropertyName]);
}
}
}
What you have is an object, not an array. What you need to do is, use the
Object.keys()
method and obtain a list of keys which is the field names in that object. Then you could use a simple for loop to iterate over the keys and do whatever you need to do.

Categories

Resources