How can I get object by key? [duplicate] - javascript

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 7 years ago.
var test = [
{
id : 'user01',
pos0 : 2
},
{
id : 'user01',
pos0 : 3
},
{
id : 'user02',
pos1 : 5
},
{
id : 'user02',
pos1 : 6
},
{
id : 'user03',
pos2 : 8
},
{
id : 'user03',
pos2 : 9
}
]
This is example data,
and
I want if I passed 'pos2', get test[4] and test[5].
//like this :
function getObjectByKey(array, key){
// dosomething
};
..
var testArray = getObjectByKet(test, 'pos2');
I tried to use $.inArray or $.map, but how to use them.
How can i do this?
Regards.

Please try this,
function getObjectByKey(array, key){
var users=[];
$.map(array, function (user, index) {
if (user[key])
users.push(user)
});
return users;
};
hope this will help you.
Also change your function calling. You miss spelled the function name
Try this while calling the method
var testArray = getObjectByKey(test, 'pos2');

I would suggest to use Array.prototype.map() method to iterate an array. Like this:
var test = [
{
id : 'user01',
pos0 : 2
},
{
id : 'user01',
pos0 : 3
},
{
id : 'user02',
pos1 : 5
},
{
id : 'user02',
pos1 : 6
},
{
id : 'user03',
pos2 : 8
},
{
id : 'user03',
pos2 : 9
}
]
var user;
test.map(function(v) { if(v.id == 'user03') user = v; });
Here is a FIDDLE.

Related

Displaying clean results of autocomplete [duplicate]

This question already has answers here:
jQuery UI Autocomplete use startsWith
(6 answers)
Closed 3 years ago.
I found this code online that gives options for autocomplete and I would like to give the options which start the key in letters. For example, if the alphabet 'a' is keyed in, I just want to give options start with 'a' not the options contain 'a', so from the code, when I key in 'a', I only want to display apple, not pineapples. How can I do that?
var x = [
{ label : 'apple', value : 'Delicious' },
{ label : 'pineapples', value : 'Delicious' },
{ label : 'kiwi', value : 'Yummy' },
{ label : 'kiwiooo', value : 'aaa' },
{ label : 'lemon', value : 'Sour' }
];
$( "#fruit" ).autocomplete({
source: x,
focus : function(){ return false; }}).on( 'autocompleteselect',
function( e, ui ){
var t = $(this),
details = $('#taste'),
label = ( e.type == 'autocompleteresponse' ? ui.content[0].label :
ui.item.label ),
value = ( e.type == 'autocompleteresponse' ? ui.content[0].value :
ui.item.value );
t.val( label );
details.val( value );
return false;});
The solution is pretty easy. I found the filter method used just for that. All that needs to be done is replacing that function with this:
// Overrides the default autocomplete filter function to and find only from the beginning of the string
<script>
$("#fruit").autocomplete({ source: function(request, response) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(myArray, function(item){
return matcher.test(item);
}));
}
});
</script>
There is another solution which i have used before.
source: function(request, response) {
var filteredArray = $.map(orignalArray, function(item) {
if( item.value.startsWith(request.term)){
return item;
}
else{
return null;
}
});
response(filteredArray);
}

How to get values in Json Array and use each of them separately

I have a JSON and I Want to separate each field of that in array part and then I want to use of each field separately and put them in separate array.
for example I have two part in my array and I want to divide the first part too room 1 and second part in room 2 .
I have to send Json to my second page with format room1 and room 2. and I do not know how can I do this
my json is like this right now :
"rooms": [
{
"adultcount": "1",
"childcount": "1,1"
},
{
"adultcount": "1",
"childcountandage": "0 "
}
]
but I want to change it like this :
"rooms": [
{
"rooms1": {
"adultcount": "1",
"childcount": "1,1"
}
},
{
"rooms2": {
"adultcount": "2",
"childcount": "10,1"
}
}
]
then I need to use them.
how can I do this with jquery ?
there is no need to change the json code I just wrote the sample the new json to define better.
here is my code :
$( document ).ready(function() {
var research={"rooms":[{ "adultcount":"1","childcount":"1,1" },{ "adultcount":"1","childcountandage":"0 " }] }
var adultcount = research.rooms[0].adultcount;
var childcount = research.rooms[0].childcount;
});
Since you have an array that you want to make into an object and the property name seems to be the index inside the array, you can use a basic array.reduce:
var rooms = [
{ "adultcount":"1", "childcount":"1,1" },
{ "adultcount":"2", "childcount":"10,1" }
];
var roomsMap = rooms.reduce( function( map, room, index ) {
map[ 'room' + ( index + 1 ) ] = room;
return map;
}, {} );
var otherRoomsMap = rooms.map( function( room, index ) {
var wrapper = {};
wrapper[ 'room' + ( index + 1 ) ] = room;
return wrapper;
} );
console.log( roomsMap );
console.log( otherRoomsMap );
edit:
I have added the other example of keeping the array and just wrapping the objects isnide another object, but I have no idea what advantage that would give over the original array.
You can access your json array using loop
$.each(research, function (key, value) {
var adultcount = value.adultcount;
var childcount = value.childcount;
console.log("Adult count is:"+value.adultcount);
console.log("Child count is:"+value.childcount);
});
Try this:
var research={"rooms":[{ "adultcount":"1","childcount":"1,1" },{"adultcount":"1","childcountandage":"0 " }] };
var newResearch = {"rooms": []};
research.rooms.forEach(function(r) {
newResearch.rooms.push({"room1": r[0], "room2": r[1]});
});
console.log(newResearch);

how to loop inside an array that is inside an array in javascript?

I have problems while looping through an array. That is, inside an object which is inside of an array in javascript. Below is my loop and under is my object.
I want retrieve the names of the objects. please, compare my $('#searchbox').keypress function and my var animals_data object
$('#searchbox').keypress(function (e) {
if (e.which == 13) {
var search_text = $('#searchbox').val();
console.log(search_text)
var filteredData = {
animalsR: animals_data.category.animalsR.filter(function(d){
if (d.name.search(search_text) > -1){
return true;
}
return false;
})
};
var source = $("#album-template-Reptile-result").html();
var template = Handlebars.compile(source);
var html = template(filteredData);
$('#content').html(html);
}
});
var animals_data = {
category : [{
name : "Reptiles",
animalsR : [
{
image1 : "url" ,
image2 : "url" ,
name : "Snake",
description : "text"
},
{
image1 : "url",
image2 : "url",
name : "Crocodilia",
description : "text"
}
]
}]
};
You can get first element in array via [0], category in your case is an Array
animals_data.category.animalsR.filter
// ^---- your error here, it's an array
For iterating arrays you can use Array.prototype.forEach()
animals_data.category[0].animalsR.forEach(function(e){
// do something ...
})
But what if I have many objects in the array category. Each of which contains an array that I want to itterate through.
For that you can use nested Array.forEach() method, like this:
animals_data.category.forEach(function(a) {
a.animalsR.forEach(function(e) {
// do something
});
});

Issue Pushing values in to objects Javascript

Have some issue with push the values in to the javascript array object. Please any one give me the perfect solution
Class code :
var myfuns = ( function(undefined) {
var myarr ={};
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
}
}
function _getList() {
return $.extend(true, {}, myarr);
}
return {
add : _add,
getList : _getList
}
}());
Here am calling and manage the values and keys
function setmydetails(){
var my_param = {
current_info : {
pg : '#tset',
no : 12,
name : "john",
row : 0,
},
userprofile : [],
class : [],
marks : [],
games : []
};
myfuns.add(my_param);
}
Now i got the array
myfuns.getList() // GOT proper array what i passed in my_param
Question : How to modify the existing values from any one of the Inner array from the myarr Obj
Ex: Once First array created later have to modify some from "myarr.current" = > Change current_info.row to 2222
Similar i have to add some array in to " myarr.class " etc
I would like to say try this one not tested
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
$.extend( myarr.current, arrayparam);
}
}
proper source : https://api.jquery.com/jquery.extend/

Get random json object

I want to get random hotelCode (for example CUNMXSAKU but randomly) object.
Is it possible to have this object randomly in javaScript or Jquery.
My JSON:
var simulatedHotelCodes = {
"CUNMXSAKU" : {
"roomCodes" : "DEAL, JRST, JPOV, JSSW, PJRS, PJOV, PJSW, RMOV, RMOF, PRES"
},
"CUNMXMAYA" : {
"roomCodes" : "ROAI, FVAI, DXAI, CAAI, SUAI, CABA, SIGA, PRAI, POFA, ROOM, FMVW, DELX, CASA, SUIT, CASI, SIGN, PROF, PROFS"
},
"CUNMXDPAV" : {
"roomCodes" : "GDVW, MRNA, FMLY, DFAM, HNDO, OCVW, DOLP, FMOV, PCDO, HNOC, PCOV, PFOV, ROHO"
},
"CUNMXHIDD" : {
"roomCodes" : "JRST, JRSU, DOME"
},
"CUNMXDSAN" : {
"roomCodes" : "DEAL, DELX, DEXBA, DXOF, DOFB, PROV, PROF, PROB, POFC, HONY, FAMI, PRJS, DEBL, PRDD"
}
};
Output:
"CUNMXMAYA" : {
"roomCodes" : "ROAI, FVAI, DXAI, CAAI, SUAI, CABA, SIGA, PRAI, POFA, ROOM, FMVW, DELX, CASA, SUIT, CASI, SIGN, PROF, PROFS"
}
or
"CUNMXHIDD" : {
"roomCodes" : "JRST, JRSU, DOME"
}
Randomly
Thanks in advance
I'd use Object.getOwnPropertyNames() to get an array of all the properties, then pick a random index.
var simulatedHotelCodes = {
"CUNMXSAKU" : {
"roomCodes" : "DEAL, JRST, JPOV, JSSW, PJRS, PJOV, PJSW, RMOV, RMOF, PRES"
},
"CUNMXMAYA" : {
"roomCodes" : "ROAI, FVAI, DXAI, CAAI, SUAI, CABA, SIGA, PRAI, POFA, ROOM, FMVW, DELX, CASA, SUIT, CASI, SIGN, PROF, PROFS"
},
"CUNMXDPAV" : {
"roomCodes" : "GDVW, MRNA, FMLY, DFAM, HNDO, OCVW, DOLP, FMOV, PCDO, HNOC, PCOV, PFOV, ROHO"
},
"CUNMXHIDD" : {
"roomCodes" : "JRST, JRSU, DOME"
},
"CUNMXDSAN" : {
"roomCodes" : "DEAL, DELX, DEXBA, DXOF, DOFB, PROV, PROF, PROB, POFC, HONY, FAMI, PRJS, DEBL, PRDD"
}
};
var properties = Object.getOwnPropertyNames(simulatedHotelCodes);
var index = Math.floor(Math.random() * properties.length);
var output = {};
output[properties[index]] = simulatedHotelCodes[properties[index]];
console.log(output);
If you only care about modern browsers, check #dave's answer which is cleaner (and it probably has a better performance). If you want a cross-browser solution here there is an option:
// Define amount of json objects
var length = 0;
for (var key in json)
length++;
// Get random index and iterate until get it
var rnd = Math.floor(Math.random()*length),
i = 0,
obj;
for (var key in json) {
if (i == rnd) {
obj = {};
obj[key] = json[key];
break;
}
i++;
}
// obj has the random item
Note that you would need the random selected key to use obj. You could change this:
obj = {};
obj[key] = json[key];
to this:
obj = json[key];
to save only the random item value.
http://jsfiddle.net/paska/m2y7gvnp/1/
Yes it is possible. But it would be more easy if you put those object in array so that you can access those object through array index. As array index is an integer, you can randomly generate that array index and then access that object.

Categories

Resources