Pushing value to empty array [duplicate] - javascript

This question already has answers here:
How to append something to an array?
(30 answers)
Closed 5 years ago.
Trying to push the value I get from the onlick to a empty array and I cant seem to get it right.
var result = [];
$('#submitButton').click(function(){
var textField = $('#textField').val();
$('#result').append(textField, '<br/>');
$('#textField').val('');
result($(this).val());
});

Use this to push values in array
result.push($(this).val())

var result = [];
$('#submitButton').click(function(){
var textField = $('#textField').val();
$('#result').append(textField, '<br/>');
$('#textField').val('');
result.push($(this).val()); /* You have to use push method */
});

In your code, this refers to button(#submitButton), not to element of which you want to access value.
Use Array.prototype.push to push value in array
var result = [];
$('#submitButton').click(function() {
var textField = $('#textField').val();
$('#result').append(textField, '<br/>');
$('#textField').val('');
result.push(textField);
});

Related

Create JSON Array key dynamically in JavaScript [duplicate]

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;

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/

Access items within an JS object, append to each DOM element in order [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 8 years ago.
I have the following object which has been passed from PHP
var phpVars = {"embedCode0":"<iframe id="player_0"></iframe>",
"embedCode1":"<iframe id="player_1"></iframe>",
"embedCode2":"<iframe id="player_2"></iframe>",
};
My HTML contains a matching number of <div class="video-container"></div> elements. I want to append each of the array items to each div in order. So that "embedCode0" is appended to the first div, "embedCode1" is appended to the second div and so on.
My jQuery function looks like this:
function vids(){
var $video = $('div.video-container');
$video.each(function(index) {
var $iframe = phpVars.embedCode + index;
$(this).append($iframe);
});
}
The function returns NaN. I have attempted to convert the index to a string but have not been able to succeed.
How can I increment the "embedCode" string?
You should be trying this
var $iframe = phpVars["embedCode" + index];
instead of
var $iframe = phpVars.embedCode + index;
When you are saying phpVars.embedCode + index it tries to first evaluate phpVars.embedCode and after that concatenating index in that.

How to create dynamic two dimensional array in jquery or js [duplicate]

This question already has answers here:
How can I create a two dimensional array in JavaScript?
(56 answers)
Is it possible to create an empty multidimensional array in javascript/jquery?
(8 answers)
Closed 9 years ago.
I need to create global two dimensional array in jquery or javascript
My function is like this
<script>
var globalArray[0] = new Array();
function createArray(){
alert(globalArray[0]);
}
</script>
<div><input type='button' value='save' onclick='createArray();'> </div>
On click of that button I am getting this error "globalArray[0] is undefined"
How can I create global dynamic multi dimensional array.
if (!globalArray[index])
globalArray[index] = []; // init the array.
globalArray[index].push(name);
You have a typo with the dot:
$.("#uname").val();
Change to:
$("#uname").val();
What are you trying to do with this code?
Update: (The question was totally edited.)
Your code:
var globalArray[0] = new Array();
globalArray[0] is invalid variable name, you need first to declare the array:
var globalArray = []; // Array literal.
globalArray[0] = [] // The element at position 0 is new an array.
Intead of
if(loop == 0){
globalArray[index][0] = uname;
}else{
globalArray[index][loop++] = uname;
}
Use this
if(loop > 0){
globalArray[index][loop++] = uname;
}else{
globalArray[index][0] = uname;
}

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