This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 8 years ago.
I have JSON objects that have several properties such as an id and name. I store them in a JavaScript array and then based on a dropdownlist I want to retrieve the object from the JavaScript array based on its id.
Suppose an object has id and name, how do I select them from my array variable?
var ObjectsList = data;
var id = $("#DropDownList > option:selected").attr("value");
ObjectsList["id=" + id];
Since you already have jQuery, you could use $.grep:
Finds the elements of an array which satisfy a filter function. The original array is not affected.
So something like this:
var matches = $.grep(ObjectsList, function(e) { return e.id == id });
that will leave you with an array of matching entries from ObjectsList in the array matches. The above assumes that ObjectsList has a structure like this:
[
{ id: ... },
{ id: ... },
...
]
If you know that there is only one match or if you only want the first then you could do it this way:
for(var i = 0, m = null; i < ObjectsList.length; ++i) {
if(ObjectsList[i].id != wanted_id)
continue;
m = a[i];
break;
}
// m is now either null or the one you want
There are a lot of variations on the for loop approach and a lot of people will wag a finger at me because they think continue is a bad word; if you don't like continue then you could do it this way:
for(var i = 0, m = null; i < ObjectsList.length; ++i) {
if(ObjectsList[i].id == wanted_id) {
m = ObjectsList[i];
break;
}
}
Related
This question already has answers here:
Simplest code for array intersection in javascript
(40 answers)
Closed 4 years ago.
I can't seem to figure this out.
I have two arrays. One of the arrays contains all the IDs of the other array, plus more.
var arr1 = [1,2,3,4,5]
var arr2 = [3,5]
My first array contains a lot more information which my second array does not (many other keys). I need to find a way to select all the elements of the first array that are present in the second array and return them so that I have just the elements of arr2 but with all the additional data in arr1. How can I do this?
EDIT: I should make it clear that in the first array, I am looking for specific IDs that match the indexes of the second array. So the solutions here are really good but not quite what I'm after. Example:
[ 0: { id: 1, name: "fred" } ...]
I want to match the id with my second array, not the index. Hope this makes sense!
I implemented a set data structure few months back, this is the difference function
function difference (firstarr,secondarr) {
let diffSet = [];
for ( let i = 0; i < secondarr.length ; i++ ) {
let hasValue = secondarr.includes(firstarr[i]);
if ( ! hasValue ) {
diffSet.push(secondarr[i]);
}
}
for ( let i = 0; i < firstarr.length ; i++ ) {
let hasValue = secondarr.includes(firstarr[i]);
if ( ! hasValue ) {
diffSet.push(firstarr[i]);
}
}
return diffSet;
};
console.log(difference([1,2,3,4],[3,4]));
Use filter and includes of Array.protitype.
var arr1 = [1,2,3,4,5]
var arr2 = [3,5,7]
console.log(arr1.filter(x=>!arr2.includes(x)));
arr2.forEach(function(x){
if(!arr1.includes(x)){
arr1.push(x);
}
})
console.log(arr1);
This question already has answers here:
split string in two on given index and return both parts
(10 answers)
Closed 6 years ago.
I have a string that looks like this:
YA...Y..............
I need to create an object out of this. I was going to try to create an array from the string (but can't see how) if there was a way of doing a split on character index.
Then I was going to loop through that array and create an object.
I had a solution a bit like this:
// Creat an array
var array = [];
// Get our string length
var len = profileString.length - 1;
// Loop through our lengths
for (var i = 0; i < length; i++) {
// Get our current character
var char = profileString[i];
// Push our character into our array
array.push(char);
}
// Create our object
var obj = {};
// Loop through our array
array.forEach(function (item, index) {
// Add our item to our object
obj['item' + index] = item;
});
// Return our object
return obj;
I need to know if there is a better way of doing this.
You could use Object.create.
console.log(Object.create([...'YA...Y..............']));
ES5
console.log(Object.create('YA...Y..............'.split('')));
This question already has answers here:
Filter strings in Array based on content (filter search value)
(6 answers)
Closed 6 years ago.
I have a array in javascript containing "aassd,v_value1,asadds,v_value2, asddasd...", and I need extract the values that begin with v_ in a new array.
I used the next function to get the values, but only get the first value.
function search (array,string) {
var arr= [];
for (var i=0; i<array.length; i++) {
if (array[i].match(string)){
arr.push(i)
return arr;
}
}
return -1;
}
search(array,'v_')
Thanks.
You should use .filter() method as below:
function search (array,string) {
return array.filter(function (val) {
return val.substr(0, string.length) === string;
});
}
The filter() method returns items of array which fulfills the condition in the callback function
I think below might work. Just string match and push to new array if found.
var arr = ['aassd','v_value1','asadds','v_value2','asddasd'];
var newArr = []
substring = "v_";
for (var i = 0; i < arr.length; i++) {
if (arr[i].search(substring) === 0) {
newArr.push(arr[i]);
}
}
alert(newArr);
function search (array,string) {
var arr= [];
for (var i=0; i<array.length; i++) {
//Do not use MATCH here as you need values that STARTS WITH "v_", match will give you values like this asdasdav_asdasda also.
if (array[i].startsWith(string)){
//instead of this
//arr.push(i)
//use this , the above will push the index, this will push the VALUE(as asked in the question)
arr.push(array[i])
//remove this: as this breaks on the first true condition , hence you get one value.
//return arr;
}
}
return arr;
}
The Mistakes
Do not use MATCH for it will return values with the pattern anywhere in the string.
Use startsWith instead
Return outside the loop as it ends the loop when it matches the first time and hence you get only the first item
You should push the value not the index as asked in the question. So do this arr.push(array[i])
This question already has answers here:
Getting a list of associative array keys
(6 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
I need to group the rows out of a table that has a matching order number, and then iterate over the groupings.
I have this code working which is creating the perfect array, data-wise:
var multItems = [];
// Combine items under orders,
$('tr.order').each(function(){
var orderNum = $(this).find('.ordernumber').val();
if ( ($('tr.order .ordernumber[value="' + orderNum + '"]').length > 1 ) && !(orderNum in multItems) ){
$('tr.order .ordernumber[value="' + orderNum + '"]').each(function(){
if (!(orderNum in multItems)){
multItems[orderNum] = [];
}
multItems[orderNum].push(this);
});
}
});
// Create new tr with order totals (of each item)
for (var i = multItems.length - 1; i >= 0; i--) {
// Code
};
But it creates an array with a length of 0, apparently, where multItems = [], but multItems[orderNumber] is defined... just with no way to access it if I don't know the order numbers.
I could make an array of the order numbers separately, but that feels like it must be the long way round. If I just create a numbered array, how do I know which number to pop the items from the orders into?
With your current code you have
var orderNum = $(this).find('.ordernumber').val();
where val() returns a string and not a number. So when you are doing multItems[orderNum] it is a string.
For the current code to work, you want to use a for in loop.
for (var prop in multItems) {
if( multItems.hasOwnProperty( prop ) ) {
console.log(multItems[prop]);
}
}
FYI: Order is not guaranteed. Also you should be using an object {} and not an array here.
Now the other thing you can do is to use parseInt to change the string into a number and than magically your for loop would start working. [This is assuming that ordernumber is a numeric value]
var orderNum = parseInt($(this).find('.ordernumber').val(), 10);
My question is related to this question. You will have to first read it.
var ids = "1*2*3";
var Name ="John*Brain*Andy";
var Code ="A12*B22*B22";
Now that I have an array of javascript objects. I want to group my objects based on CODE. So there can be duplicate codes in that code string.
As per the above changed strings, I have same code for Brain and Andy. So, now I want two arrays. In one there will be only one object containing details of only John and in the other object there will be two objects containing details of Brain and Andy.
Just for example I've taken 3 items. In actual there can be many and also there can be many set of distinct codes.
UPDATE
I needed the structure like the one built in groupMap object by the #Pointy. But I will use #patrick's code to achieve that structure. Many thanks to both of them.
It is a little hard to tell the exact resulting structure that you want.
This code:
// Split values into arrays
Code = Code.split('*');
Name = Name.split('*');
ids = ids.split('*');
// cache the length of one and create the result object
var length = Code.length;
var result = {};
// Iterate over each array item
// If we come across a new code,
// add it to result with an empty array
for(var i = 0; i < length; i++) {
if(Code[i] in result == false) {
result[ Code[i] ] = [];
}
// Push a new object into the Code at "i" with the Name and ID at "i"
result[ Code[i] ].push({ name:Name[i], id:ids[i] });
}
Will produce this structure:
// Resulting object
{
// A12 has array with one object
A12: [ {id: "1", name: "John"} ],
// B22 has array with two objects
B22: [ {id: "2", name: "Brain"},
{id: "3", name: "Andy"}
]
}
Split the strings on "*" so that you have 3 arrays.
Build objects from like-indexed elements of each array.
While building those objects, collect a second object that contains arrays for each "Code" value.
Code:
function toGroups(ids, names, codes) {
ids = ids.split('*');
names = names.split('*');
codes = codes.split('*');
if (ids.length !== names.length || ids.length !== codes.length)
throw "Invalid strings";
var objects = [], groupMap = {};
for (var i = 0; i < ids.length; ++i) {
var o = { id: ids[i], name: names[i], code: code[i] };
objects.push(o);
if (groupMap[o.code]) {
groupMap[o.code].push(o);
else
groupMap[o.code] = [o];
}
return { objects: objects, groupMap: groupMap };
}
The "two arrays" you say you want will be in the "groupMap" property of the object returned by that function.