Followup question from here: Old question
This result come from other file script called localStorage.result
output is: [{"url_field":"yahoo","enabled":true},{"url_field":"google","enabled":true},{"url_field":"bing","enabled":true}]
To extract specific ID/value I use this code:
var myurlsave = localStorage.result;
var arr = myurlsave.map(function(a) {
return a.url_field;
});
This code above has no result or output. But when I write manually the result of localStorage.result like this:
var myurlsave = [{"url_field":"yahoo","enabled":true},{"url_field":"google","enabled":true},{"url_field":"bing","enabled":true}];
var arr = myurlsave.map(function(a) {
return a.url_field;
});
There will be a result that I need: var arr = ["yahoo", "google", "bing"]
But I need to use the var myurlsave = localStorage.result because this dynamical change base on users input.
Thank you for the help
From the looks of your logic it would appear that localStorage.result is a string. In this case you need to deserialise it to an object:
var myurlsave = JSON.parse(localStorage.result);
var arr = myurlsave.map(function(a) {
return a.url_field;
});
Related
The values in my spreadsheet are these:
/2021/
/20212022/
/2022/
/20222023/
/2023/
To try to find these values in a string and then replace with /####/ I tried creating a map:
var sheet = SpreadsheetApp.getActive().getSheetByName('One')
var liga = 'https://int.testestest.com/national/united-states/mls/2022/regular-season/r66725/'
var years = sheet.getRange('One!A10:A14').getValues().flat();
var mapObj = {one: years[0],two: years[1],three: years[2],four: years[3],five: years[4]};
var liga_substitute = liga.replace(/\b(?:one|two|three|four|five)\b/gi, matched => mapObj[matched]);
var liga_final_subs = liga_substitute.replace('one','/####/').replace('two','/####/').replace('three','/####/').replace('four','/####/').replace('five','/####/')
But the result after substitution remains the same:
https://int.testestest.com/national/united-states/mls/2022/regular-season/r66725/
My final expected result is:
https://int.testestest.com/national/united-states/mls/####/regular-season/r66725/
And in var liga_final_subs = exist the risk of finding these parts of text in the wrong places and replacing what shouldn't.
How should I go about doing this correctly?
Not sure what you trying to gain. Here is the code that does the job (I hope):
var liga = 'https://int.testestest.com/national/united-states/mls/2022/regular-season/r66725/'
var years = [
'/2021/',
'/20212022/',
'/2022/',
'/20222023/',
'/2023/',
];
var liga_final_subs = liga;
years.forEach(x => liga_final_subs = liga_final_subs.replace(x, '/####/'));
console.log(liga_final_subs);
I am trying to append an array to an array. I am expecting the output to be something like:
[[Dep,POR],[14073,99.25],[14072,0.06]]
But I am getting:
Dep,POR,14073,99.25,14072,0.06
Here's what I have so far:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = ['Dep','POR'];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_por = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(hist_por);
}
When you initialize hist_por, you want that to be a 2-D array whereas you currently have just a single array. So you would want to change its instantiation to:
hist_por = [['Dep','POR']]; // [[ ... ]] instead of [ ... ]
Also per #justrusty's answer, you need to JSON.stringify(hist_por) when you pass it to document.write(). This is the more important piece so his answer should be accepted.
So the whole code block would become:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = [['Dep','POR']];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_rop = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(JSON.stringify(hist_por));
}
This may help you https://codepen.io/anon/pen/xQLzXx
var arr = ['foo','bar'];
var arr2 = ['baz', 'boo']
arr.push(arr2);
console.log(arr);
document.write(arr);
document.write("<br>");
document.write(JSON.stringify(arr));
It's basically just the way it writes it to document. If you log it in console you'll see the array appended. Or if you JSON.stringify() first it will show as you expect.
My advice is ALWAYS console.log() so you can see exactly how the data is structured
The others have already pointed out what the problem is (+ there's a typo in one of your variable names - arr_rop vs arr_por). Here's an ES6 version that will break in older browsers, for learning purposes:
function get_historical() {
const well = document.getElementById('wellSelect');
const selected_well = well.options[well.selectedIndex].value;
const hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
const hist_por = Object.values(hist_json_obj).reduce(
(arr, item) => [...arr, [item.dep, +item.por]],
[["Dep", "POR"]]
);
document.write(JSON.stringify(hist_por));
}
What I'm trying to do is from a comma separated text (like this one):
hello,test,ciao
Get a javascript array with a predetermined value.
I know how to split a comma-separated list, but I don't know how to add a value inside them.
Actual code:
HTML
<input onkeyup="test()" type="text" id="origin">
<div id="response">
</div>
JAVASCRIPT:
function getValue(){
var returnV = $("#origin").val();
return returnV
}
function test(){
var origin = getValue();
var array = origin.split(',');
console.log(array)
}
OUTPUT
["hello", "test", "ciao"]
WHAT I'M TRYING TO GET
{
"hello":"predetermined value",
"test":"predetermined value",
"ciao":"predetermined value",
}
I think this question is interesting because this way yo can, for example, create new configurations with a starter value and add custom confirgurations for each of them later. I know that the split part is already replied on stackoverflow, what I'm having trouble with is with adding the default values :), thank you very much in advance.
didn't want to change your code so much. just have a look up to object creation.
function getValue(){
return document.getElementById("origin").value
}
function test(){
var obj = {}
var origin = getValue();
origin.split(", ").forEach(function(e) {
obj[e] = "predeterminated value";}
);
console.log(obj);
}
<input onkeyup="test()" type="text" id="origin">
<div id="response">
</div>
Have you tried iterating over the array? Like this:
function getValue(){
var returnV = $("#origin").val();
return returnV
}
function test(){
var origin = getValue();
var object = {}
var array = origin.split(',');
array.forEach((item) => {
object[item] = "predeterminated value"
}
console.log(object)
}
A couple notes: try to give more meaningful names to your variables; the word is "predetermined",
Store your output to a variable:
var output=["hello", "test", "ciao"]
Then do something like this with it:
var newObject={};
for(var i in output){
var property=output[i];
newObject[property]='predeterminated value';
}
Example JSFiddle (open console to see result)
Split your string and then use Array.prototype.reduce to build an object from it.
var original = "hello,test,ciao";
var obj = original.split(',').reduce(function(p,c) {
p[c] = "predeterminated value";
return p;
}, {});
console.log(obj);
It's not exactly clear where predeterminated value is supposed to come from. If it's the same for all properties of your object, then this will work as-is. If it's not, you'll have to figure out how to select the right value.
Hey you can follow the below code snippet this will help
function getValue(){
var returnV = 'hey,your,input,keys,goes,here';
return returnV;
}
function test(){
var origin = getValue();
var array = origin.split(',');
var finalObj = {};
var defaultVal = 'pre-def';
for(var i=0;i<array.length;i++){
finalObj[array[i]] = defaultVal;
}
console.log("arry",array)
console.log("converted",finalObj)
}
test();
I have an array containing 3 elements
var a = [];
a["username"]=$scope.username;
a["phoneNo"]=$scope.phoneNo;
a["altPhoneNo"]=$scope.altPhoneNo;
Now, I want to send this data to server in JSON format. Therefore, I used
var aa = JSON.stringify(a);
console.log("aa = "+aa);
But the console displays empty array
aa = []
How can I convert this array into JSON?
That's not the correct way to add elements to an array, you're adding properties instead.
If you did console.log(a.username); you'd see your $scope.username value.
You could either do
var a = [];
a.push({"username": $scope.username});
a.push({"phoneNo": $scope.phoneNo});
a.push({"altPhoneNo": $scope.altPhoneNo});
But it looks more like what you're trying to do is
var a = {};
a["username"] = $scope.username;
a["phoneNo"] = $scope.phoneNo;
a["altPhoneNo"] = $scope.altPhoneNo;
That is, you want your a to be an object if you're going to add properties to it.
And that would be better written as
var a = {};
a.username = $scope.username;
a.phoneNo = $scope.phoneNo;
a.altPhoneNo = $scope.altPhoneNo;
I have an array:
var pages = new Array();
I want to push my pages data to this array like this:
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
pages_order.push({datatype:info});
});
but this code doesn't replace datatype as variable, just puts datatype string as a key.
How do I make it place there actual string value as a key name?
I finally saw what you were trying to do:
var pages = new Array();
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
var temp = {};
temp[datatype] = info;
pages_order.push(temp);
});
$('li.page').each(function () {
//get type and info, then setup an object to push onto the array
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
obj = {};
//now set the index and the value for the object
obj[datatype] = info;
pages_order.push(obj);
});
Notice that you can put a comma between variable declarations rather than reusing the var keyword.
It looks like you just want to store two pieces of information for each page. You can do that by pushing an array instead of an object:
pages_order.push([datatype, info]);
You have to use datatype in a context where it will be evaluated.
Like so.
var pages = [];
$('li.page').each(function () {
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
record = {};
record[datatype] = info;
pages_order.push(record);
});
You only need one var it can be followed by multiple assignments that are separated by ,.
No need to use new Array just use the array literal []
You may add below single line to push value with key:
pages_order.yourkey = value;