Create JSON Array key dynamically in JavaScript [duplicate] - javascript

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 3 years ago.
I'm Having a JSON that is getting creates in for-loop.
Here my main requirement is to create the Key from a predefined variable.
Here is the code that I'm using.
var rows =["Hello Trt", "Ho there", "I'm up"];
var name="Hello";
var jsonData = {};
var intentName=[];
var mainPersonel = {};
var intents = {};
intents.intentName = rows;
mainPersonel.intents=intents;
console.log(JSON.stringify(mainPersonel));
Looking into the other SO posts, I'm able to find on how can I replace intents variable, but here in my case, I want to replace intentName with name in the output.
Expected output is
{"intents":{"Hello":["Hello Trt","Ho there","I'm up"]}}
Please let me know on how can I achieve this.
Thanks

I think the below code satisfies your requirement.
var rows =["Hello Trt", "Ho there", "I'm up"];
var name="Hello";
var jsonData = {};
var intentName=[];
var mainPersonel = {};
var intents = {};
intents[name]= rows;
mainPersonel.intents=intents;
console.log(JSON.stringify(mainPersonel));

You can do like this:
intents[name]= rows;

Related

Collect values from a spreadsheet, look for those values in a string and replace

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

How to add new a new property to an object in an array? [duplicate]

This question already has answers here:
How to append something to an array?
(30 answers)
Closed 5 years ago.
var fruits = [];
fruits[0] = {name:"apple", stock:"1box"}
fruits[1] = {name:"banana", stock:"2box"}
fruits[2] = {name:"banana", stock:"3box"}
so in case of this object
is there any simple way to add new field inside of list like this?
for example
fruits[0] = {name:"apple", stock:"1box", **taste:"good"**}
like this.
i tried create new template and copy original data and paste to the new template, for example
function fruit_2(name, stock, taste){
this.name = name;
this.stock = stock;
this.taste = taste;
}//create new template
and re-add element from the fruit[0] and then fruit[1] to new template like this
but i was wondering if there is easier or faster way.
thank you for reading my question.
i will appreciate any help! thanks!
I add an taste element to each object, and fill it with the value "good"+ index of the element. Here is a simple demo:
var fruits = [];
fruits[0] = {name:"apple", stock:"1box"};
fruits[1] = {name:"banana", stock:"2box"};
fruits[2] = {name:"banana", stock:"3box"};
for(var index=0;index<fruits.length;index++){
fruits[index].taste="good "+index;
}
console.log(fruits);
Easiest way to append is either use:
fruits[0]["taste"] = "good";
or:
fruits[0].taste = "good";
The easiest way to add a property to existing object for each element in array is to itterate over the array and set the property to the desired value using
element[index].desiredProperty = desiredValue;
For example see following fiddle: https://jsfiddle.net/to70xe4j/1/

How do I convert an array from the ViewBag to a JScript array using Razor Syntax? [duplicate]

This question already has answers here:
How to return Json object from MVC controller to view
(4 answers)
Closed 7 years ago.
I am trying to re-code the following razor syntax to be workable code and am stuck:
var ServiceIndex = #ViewBag.ServiceID ;
var ServiceName = #ViewBag.ServiceName ;
var ServiceNotes = #ViewBag.ServiceNotes ;
My problem is that right now the ViewBag for those 3 arrays is empty and so it pukes on the lone semicolon.
You need to translate it into JSON on a server-side.
<script>
var ServiceNotes = #(Html.Raw(JsonConvert.SerializeObject(ViewBag.ServiceNotes)));
var ServiceName = #(Html.Raw(JsonConvert.SerializeObject(ViewBag.ServiceName)));
var ServiceIndex = #(Html.Raw(JsonConvert.SerializeObject(ViewBag.ServiceIndex)));
</script>
Then access it directly in JS.
The empty array is correctly processed by JsonConvert, so, if it is empty you will get something like
var ServiceNotes = [];
For the convenience of debugging and avoiding nested function calls you can also split serializing and output.
#{
string serviceNotesJson = JsonConvert.SerializeObject(ViewBag.ServiceNotes);
string serviceNameJson = JsonConvert.SerializeObject(ViewBag.ServiceName);
string serviceIndexJson = JsonConvert.SerializeObject(ViewBag.ServiceIndex);
}
#section scripts
{
<script>
var ServiceNotes = #(Html.Raw(serviceNotesJson));
var ServiceName = #(Html.Raw(serviceNameJson));
var ServiceIndex = #(Html.Raw(serviceIndexJson));
</script>
}

create variable name function [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript dynamic variable name
I'm trying to create a function in javascript that has a name dependent on a variable.
For instance:
var myFuncName = 'somethingWicked';
function myFuncName(){console.log('wicked');};
somethingWicked(); // consoles 'wicked'
I can't seem to figure out a way to do it.... I tried to eval it, but then when I try and use the function at a later time it 'doesnt exist'.. or more exactly I get a ReferenceError that the function is undefined...
Any help would be appreciated.
You could assign your functions to an object and reference them like this:
var funcs = {};
var myFuncName = 'somethingWicked';
funcs[myFuncName] = function(){console.log('wicked');};
funcs.somethingWicked(); // consoles 'wicked'
Alternatively, you could keep them as globals, but you would still have to assign them through the window object:
var myFuncName = 'somethingWicked';
window[myFuncName] = function(){console.log('wicked');};
somethingWicked(); // consoles 'wicked'
var myFuncName = 'somethingWicked';
window[myFuncName] = function(){console.log('wicked');};
somethingWicked(); // consoles 'wicked'
Any time you have to create something that depends on a dynamic name for a variable you should be using a property of an object or an array member instead.
var myRelatedFunctions = {};
var myFuncName = 'somethingWicked';
myRelatedFunctions[myFuncName] = function (){console.log('wicked');};
myRelatedFunctions['somethingWicked']()

JavaScript - Using a variable to refer to a property name? [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 8 years ago.
I am creating my own object:
gridObject = new Object();
I am then using jquery to pull the contents of list item tags, which themselves are filled with tags that have specific class names:
<li row="1"><p class="department" rowitem="department">Photography</p>...</li>
I am pulling them using this code:
//make object from results
gridObject = new Object();
//get all the rows
var rowlist = $('li[row]');
for(var r=0; r<rowlist.length; r++) {
//make gridObject row element here
//get the row content
var thisrow = $(rowlist[r]).html();
//get all the p tags
var rowitems = $(thisrow + 'p.[rowitem]');
//get field name
for(var ri=0; ri<rowitems.length; ri++) {
if (r < 2) { //this is temporary just for testing
var fieldname = $(rowitems[ri]).attr('rowitem');
var fieldvalue = $(rowitems[ri]).html();
}
}
Ia m getting hung up passing this into my object. Two questions. Can an object property be made with a variable name, like so
griObject.fieldname = fieldvalue;
and can the objects have parent/child relationships such as:
gridObject.r.fieldname = fieldvalue;
in this case both r and fieldname would be variables. Or should I just be working associative arrays to achieve something similar?
This is in answer to a follow up question I posted below: "Is there a print_r equivalent in javascript" - you can use iterator, a bit more typing but does the trick:
//loop through search data
var it = Iterator(filteritems);
for(var pair in it) {
console.log("key:" + pair[0] + ", value:" + pair[1] + "\n");
}
If you want to use a variable property name, use subscript syntax:
var fieldname = 'test';
//These two lines are equivalent as long as fieldname is 'test':
gridObject[fieldname] = fieldvalue;
gridObject.test = fieldvalue

Categories

Resources