I have a JavaScript array which has the follow structure:
[{id:'id1', container:'3', routing:'4'},{id:'id2', container:'2', routing:'5'},..]
Now through the command 'push' i was able to make a copy of this array. My question is how to add a new element (NEWFIELD) to the new array, to become like this:
[{id:'id1', container:'3', routing:'4',NEWFIELD:'X'},{id:'id2', container:'2', routing:'5',NEWFIELD:'Y'},..]
You can try something like following
var arr = [{id:'id1', container:'3', routing:'4'},{id:'id2', container:'2', routing:'5'},..];
var new_arr = arr.map(function(item){
var clone = Object.assign({}, item); // Objects are pass by referenced, hence, you need to clone object
clone.NEWFIELD = clone.routing/clone.container;
return clone;
});
var arr = [{id:'id1', container:'3', routing:'4'},{id:'id2', container:'2', routing:'5'}];
// clone an array
var newArr = arr.map(function(e) {
return JSON.parse(JSON.stringify(e));
});
// add new field
newArr.forEach(function(e) {
e['NEWFIELD'] = e.routing / e.container;
});
console.log(arr);
console.log(newArr);
Related
Hi all I have problem to make some id into one array
Maybe you can help me...This image is the result
enter image description here
and this is my code
$.each(data.rows, function (i, ele) {
var tes = ele.ID;
console.log('ItemID', tes);
}
The Result that i want expect is each item in the one array like this 'ItemID = [22,2,43,2]'
const idArray = data.rows.map((r)=>r.ID)
//More verbose
const idArray = data.rows.map(function (ele){
return r.ID;
});
Map creates a loop through all the values in the array and uses the return of the function passed to create a new array.
EDIT:
I'm not sure I understand, you'd want an array of array?
const idArray = data.rows.map(function (ele){
return [r.ID];
});
var tempArray = []
$.each(data.rows, function (i, ele) {
tempArray.push(ele.ID);
}
// tempArray will be the solution
var data = [1,2,3,4]; // Assuming this array contains rows data
var resultArray = []; // Result array
var ids = data.map(function (ele){
return ele;
});
resultArray.push(ids.join(',')); // Join ids using "," separator
console.log(resultArray); // ["1,2,3,4"]
I have a function:
chatManager.connect()
.then(currentUser => {
var final = currentUser.users;
var name = [];
var arr = [];
$.each(final,function(index,val){
if(val.name != '{{Auth::user()->name}}')
{
console.log(val.id); //Harry, Ron (each in different line)
arr = name.push(val.id)
console.log(arr); //1,2 (each in different line)
var presence = val.presenceStore.store.{{Auth::user()->name}}{{Auth::user()->id}}
}
});
I want the arr to be an array like [Harry,Ron]. Why is it not working? I am new to Jquery. Please help.
arr = name.push(val.id) is your problem. push returns the array's new length, not an array. Simply replace the line with
arr.push(val.id);
I'm wanting to filter an array without changing the original array that I've sliced from. You can see that the first thing I do within the filterChange function is to splice from the original array. The original array still ends up changed as well and I don't understand why.
var MenuDisplayModule = (function ($, window, document, Handlebars) {
var module = {};
module.menuItems = [];
module.init = function () {
console.info('BreadcrumbDisplayModule Init');
};
module.template = function (array) {
module.menuItems = array;
var filteredMenuItems = array.slice(0);
_template(filteredMenuItems);
}
module.filterChange = function (filterText) {
var filteredMenuItems = module.menuItems.slice(0);
filteredMenuItems.forEach(function (item, index) {
var filteredItems = item.MenuItems.filter(function (el) {
return (el.MenuText.includes(filterText));
});
filteredMenuItems[index].MenuItems = filteredItems;
})
_template(filteredMenuItems);
}
function _template(filteredMenuItems) {
var menu_items_source = $("#menu-items-template").html();
var menu_items_template = Handlebars.compile(menu_items_source);
$("#menu-items-placeholder").empty().html(menu_items_template({ menuItems: filteredMenuItems }));
}
return module;
}(window.jQuery, window, document, window.Handlebars));
So it appears I didn't understand splice. Specifically the shallow aspect of it. Since I was wanting to filter on a sub array of the array I was trying to copy I ended up not getting an actual copy.
Instead of copying the array I'm creating a new array and pushing the results of the filter to it. Taking with it the un-filtered properties from the original array.
module.filterChange = function (filterText) {
var filteredMenuItems = [];
module.menuItems.forEach(function (item, index) {
var filteredItems = item.MenuItems.filter(function (el) {
return (el.MenuText.includes(filterText));
});
filteredMenuItems.push({
HeaderText: item.HeaderText,
ID: item.ID,
MenuItems: filteredItems
})
})
_templateOnChange(filteredMenuItems);
}
If you want to filter the Array and create a new one with the filtered contents and leave the old one unchanged I suggest
newArray = oldArray.filter(function(item) { return item.wantThis === true; })
Now you have newArray consisting of only those Objects which have property
item.wantThis === true
In you example you are using slice() which in my experience looks very much like splice() (which will can mutate the Array).
I suggest you simply stick to using filter().
But why are you making so many slice copies?
It would help if you posted an example of an Object in the array you receive.
Form looking at you example it seems that filteredItems is a private var to the previous ForEach loop, if you change that active part of your code to....
module.filterChange = function (filterText) {
var filteredMenuItems = module.menuItems.slice(0);
var filteredItems; // declare the var outside of the .forEach
filteredMenuItems.forEach(function (item, index) {
filteredItems = item.MenuItems.filter(function (el) {
return (el.MenuText.includes(filterText));
});
filteredMenuItems[index].MenuItems = filteredItems;
})
_template(filteredMenuItems);
}
It might work.
The effect of your filteredItems is..
filteredMenuItems.forEach(function(item) {
item.MenuItems = item.MenuItems
.filter(function(el) { return (el.MenuText.includes(filterText)); });
})
So your item.MenuItems will get smaller with each filter.
For example I have brunch of data like below:
HTML:
<p class="test-tag">abc+dd</p><p class="test-tag">gf+sx</p>
and store in JavaScript in array form
var text = ["abc+dd","gf+sx"];
And I must return an array like below:
var res = [["abc", "dd"],["gf", "sx"]];
What's the best way to do this?
Something like below should work..
var finalArr = [];
$('.test-tag').each (function (){
var value = $(this).text;
var subArr = value. map(function (b){
return b.split('+');
})
finalArr. push(subArr);
})
You can map over your array and use split:
Example JSBin
var text = ["abc+dd","gf+sx"];
var array = text.map(function(v) {
return v.split('+');
});
I'm looping through some HTML form elements on a page like so.
var itemsArray = new Array();
$('input[type="text"].qty').each(function(index) {
if($(this).val()) {
itemsArray[index]['qty'] = $(this).val();
itemsArray[index]['itemPrice'] = $(this).parents('.control-group').find('.itemPrice').val();
itemsArray[index]['itemID'] = $(this).parents('.control-group').find('.itemID').val();
}
});
The index i'm hoping to be 0,1,2,3 etc.. like a regular array. With the sub elements being associative and assigned to various values.
I'm getting this error in the console.
TypeError: itemsArray[index] is undefined
You need to make sure each item in the outer array is initialized before you start using it. Note, I changed to object notation below just for clarity.
$('input[type="text"].qty').each(function(index) {
if($(this).val()) {
itemsArray[index] = {};
itemsArray[index].qty = $(this).val();
itemsArray[index].itemPrice = $(this).parents('.control-group').find('.itemPrice').val();
itemsArray[index].itemID = $(this).parents('.control-group').find('.itemID').val();
}
});
Consider using an array of objects. Arrays in Javascript are not really intended to be used in the way you are (the multidimensional part). Also itemsArray = [] is preferred over new Array().
var itemsArray = [];
$('input[type="text"].qty').each(function(index) {
if($(this).val()) {
itemsArray.push({
qty : $(this).val(),
itemPrice : $(this).parents('.control-group').find('.itemPrice').val(),
itemID : $(this).parents('.control-group').find('.itemID').val()
});
}
});
It means what it says. itemsArray[index] is undefined, and you cannot assign properties on this. Notice that you don't have a "multidimensional array", but just an array of objects. For each new index, you will need to create a new object.
var $this = $(this);
if ($this.val()) {
var $parent = $(this).parents('.control-group'); // .closest() should suffice
itemsArray[index] = {
qty: $this.val(),
itemPrice: $parent.find('.itemPrice').val(),
itemID: $parent.find('.itemID').val()
};
}