I'm pretty new to JavaScript and need to create a JSON with number of keys and values (pushed into the variable newWord), without separating them. The thing is that I don't know what would be the length it in advenced (for that I am using a for loop to push each of the keys names and values):
let langName = document.querySelectorAll('.langName');
let langInput = document.querySelectorAll('.langInput');
let newWord = new Array()
for (let i = 0; i < langName.length; i++) {
let l = langName[i].value;
let w = langInput[i].value
newWord.push({[l]: w})
}
firebase.database().ref(`content/words/`).push(
newWord
)
So, my result right now is:
While my desired result would be:
Does anyone know how do I get rid of the indexes (0, 1) and push a string key with a string value?
Edit: I want the for loop to add to the same object in this array, instead of creating a new object inside of it.
Thanks! 😁
push is used to insert in a list in firebase database. Using set, you can store as key-value objects.
let langName = document.querySelectorAll('.langName');
let langInput = document.querySelectorAll('.langInput');
let newWord = {};
for (let i = 0; i < langName.length; i++) {
let l = langName[i].value;
let w = langInput[i].value
newWord[l] = w;
}
firebase.database().ref(`content/words/`).set(
newWord
)
Related
I am trying to filter the array 'employee_name' consisting of NaNs and one string element, to exclude any element BUT the string. The context is that I have a spreadsheet containing employee's birth dates, and I'm sending an email notification in case there's a birthday two days from today. My variables look like this:
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Employees');
var range = ss.getRange(2, 1, ss.getLastRow()-1, 1); // column containing the birth dates
var birthdates = range.getValues(); // get the `values` of birth date column
var today = new Date ();
var today = new Date(today.getTime());
var secondDate = new Date(today.getTime() + 48 * 60 * 60 * 1000);
var employee_name = new Array(birthdates.length-1);
And the loop:
for (var i=0;i<=birthdates.length-1;i=i+1){
var fDate = new Date(birthdates[i][0]);
if (fDate.getDate() == secondDate.getDate() &&
fDate.getMonth() == secondDate.getMonth()){
//define variables for outgoing email
for (var j=0; j<=birthdates.length-1;j=j+1){
employee_name[j] = [NaN];
}
employee_name[i] = ss.getRange(i+2,6);
employee_name[i] = employee_name[i].getValues();
}
}
after which the array in question looks like this
Logger.log(employee_name);
[[[Mia-Angelica]], [NaN], [NaN], [NaN], ..., [NaN]]
I have already tried the filter(Boolean), but this isn't working:
employee_name_filtered = employee_name.filter(Boolean);
Logger.log(employee_name_filtered);
returns [[[Mia-Angelica]], [NaN], [NaN], [NaN], ..., [NaN]].
I have also tried filling the non-string array entries with numeric values (instead of NaN) and then apply
employee_name_filtered = employee_name.filter(isFinite);
Logger.log(employee_name_filtered);
returns [[1.0], [2.0], [3.0], ..., [72.0]], so this filter method is working, but then I would need the 'inverse' of that because I want to keep the string.
I need the array within array to store the values at the position of the counter variable where the condition's met (similar to How to store data in Array using For loop in Google apps script - pass array by value).
This is my first time posting a question on SO, so if I overlooked any 'rules' about posting, just let me know and I will provide additional info.
Any help will be appreciated!
EDIT:
what I would like to receive in the end is simply
[[Mia-Angelica]].
The array you are using a 2 dimensional array - meaning it's an array of arrays so the filter method you are using cannot be applied in the same manner.
For this, I suggest you try the below snippet.
function cleanArray() {
var initialArray = [
['Mia-Angelica'],
['Space'],
['2'],
[NaN],
[NaN],
[NaN],
[NaN]
];
var finalArray = [];
for (let i = 0; i < initialArray.length; i++) {
var midArray = initialArray[i].filter(item => (Number.isFinite(item) && item.id !== 0) || !Object.is(item, NaN));
finalArray.push(midArray);
}
console.log(finalArray.filter(item => item != ''));
}
Note
Please bear in mind that getValues will return an Object[][] which is a two-dimensional array of values.
Reference
Apps Script Range Class;
Array.prototype.filter().
i want to save objects into an array. I have JSON objects and I want to save every object in an array to access every element alone.
Can anybody help me?
toArray = JSON.parse(res.body)
categ = Array.new
i = 0
toArray.each do |object|
newMyObject = MyObject.new(object)
categ = Array.new(i, newMyObject)
i = i+1
end
Try this one
array_from_json = JSON.parse(res.body)
objects_array = array_from_json.map { |item| MyObject.new(item) }
The issue in your code is that you are creating a new array every iteration.
I have 30 string[4] elements which contains user data. I have 30 date generic list collection. How to add each date as 5th element in each one string[] collection?
List<string> _datefromexcel = new List<string> ();
foreach(DataColumn c in dtRow.Table.Columns) {
if (Information.IsDate(c.ColumnName)) {
_datefromexcel.Add(c.ColumnName);
}
}
List<string> newlist = lst.GetRange(startrange, count);
int i = 0;
var query = from s in newlist
let num = i++
group s by num / 4 into g
select g.ToList();
var results = query.ToArray();
foreach(var item in _datefromexcel) {
results.insert(5, item);
}
This is insert all date value after 5th element.
Please advice the best way to insert each date value as 5 element in array collection.
For starters, you won't be able to "insert" anything into an array, since it has a static size. You can add things to a list, however, because a list can dynamically resize itself.
var results = query.ToList();
foreach (var item in _datefromexcel) {
results.Add(item.ToString());
}
If you need to, you can call ToArray after the foreach loop is finished:
return results.ToArray();
You can use for loop instead:
var results = query.ToArray();
for (int i = 0; i < results.Length; i++)
results[i].Add(_datefromexcel[i]);
The LINQ way will be a bit ugly:
var results = query.Zip(_datefromexcel, (l, d) => l.Concat(new[] { d }).ToList()).ToArray();
I am new to coffeescript. Please help me.
How do you find duplicated values in an array?
var arr = ['manager','manager','employee','manager',
'director','employee','manager','operatives'];
In this case it should return ['manager','employee'].
Try this:
findDuplicates = (array) ->
keys = {}
for value in array
keys[value] ?= 0
keys[value]++
(key for key, count of keys when count > 1)
arr = ['manager','manager','employee','manager', 'director','employee','manager','operatives']
console.log findDuplicates(arr)
By using filter, get more easily.
arr = ['manager','manager','employee','manager','director','employee','manager','operatives'];
filtered = arr.filter (x, i, self) ->
self.indexOf(x) == i && i != self.lastIndexOf(x)
console.log filtered # => ['manager', 'employee']
I need help in keeping track of objects in an array. I have tried giving each object an arrayIndex var, so I can splice by getting that var which represents the index in the Array.
object0.arrayIndex = 0;
object1.arrayIndex = 1;
object2.arrayIndex = 2;
object3.arrayIndex = 3;
But this is problematic if you move objects to different arrays. Objects would move from different places and therefore the arrayIndex var needs to be constantly updated.
I have done this by adding an static ID to each object. With a for loop I check each object for the corresponding object ID I want to splice
var objectID:Number = objectArrayTarget.id;
for (var t:int; t<_objectArrayLayer1.length; t++)
{
if (objectID == _objectArrayLayer1[i].id)
{
var indexOfObject:Number = (_objectArrayLayer1.indexOf(_objectArrayLayer1[i]));
}
}
_objectArrayLayer1.splice(indexOfObject, 1);
While this works is there a more efficient way of keeping track of objects in an Array? With 100+ objects this might create some slowdown
P.S. These objects are getting spliced and then pushed to a new array.
If your "Objects would move from different places" means same object from one place to another place, there is no arrayIndex needed
var indexOfObject:Number = _objectArrayLayer1.indexOf(targetObj);
if (indexOfObject >= 0) {
_objectArrayLayer1.splice(indexOfObject, 1);
}
If it means different object, like a copy, you could compare some properties to get the targetObj
for (var t:int = 0; t<_objectArrayLayer1.length; t++)
{
if (targetObj.id == _objectArrayLayer1[i].id)//assume id is unique key of the object
{
break;//i is the index here
}
}
if (i != _objectArrayLayer1.length) {//find target object
}
If the object type has a unique key, like a id, or you can make a unique key with some properties of the object, like name + "_" + order, you could use dictionary, Like Patel mentioned.
var dic:Dictionary = new Dictionary(true);
dic[obj1.id] = obj1;
dic[obj2.id] = obj2;//assume id the unique key,or you can use other key
So you can find obj like this
var obj:Object = dic[target.id]
Instead of using an Array.
I think you should use a Set implementation like Hashset
You'll get constant-time lookup, no sorting required,you can add,remove and lookup for object.