Getting the Item of Array by name of param - javascript

for (...) {
files.push(files[i]);
li_out.push({name : fileName, list_files : files});
}
How to get the Array of list_files by name?
var list_files_of_file3 = li_out[name == "file3" (?????)].list_files;

Array#find can be used in this case.
var list_files_of_file3 = li_out.find(o => o.name === "file3").list_files;
// Variable names changed for DEMO purpose
var files = [];
for (var i = 0; i < 10; i++) {
files.push({
name: 'fileName ' + i,
list_files: 'something ' + i
});
}
var res = files.find(o => o.name === 'fileName 3').list_files;
console.log(res);

How to get the Array of list_files by name?
using filter, try
var result = li_out.filter(function(item){ return item.name == "file3" });
Is it also possible to just return a property of the matching items
instead of the whole object? (below comment #MajidFouladpour)
Once you have got the result
var propertyNames = result.map(function(obj){ return obj.propertName; })

Related

Check that array of objects has all required keys

I have an object like this :
var field_arr = [{name:name},{email:email},{tel:tel}];
How to get the value of name, email or tel (property key) ? I want to use a loop to prompt user what is missing. For example, if user missed tel, there will be an alert saying tel is missing.
I don`t think you need it to be an array. Just loop over all the properties of your JSON object.
var obj = {
name: "name",
email: "",
tel: "tel"
};
$.each(obj, function(key, value) {
if (value == "") {
console.log(key + ": " + value);
}
});
Assuming you are storing those values from some fields with jQuery or something else. you can do something like :
var field_arr = [{name:"name"},{email:""},{tel:"lol"}];
jQuery.each(field_arr,function(obj){
for (var i in obj) {
if (obj[i].trim() === "") {
console.log(i + " is missing");
}
}
});
Assuming filed_arr is user input and you can't change the form of it and you want to compare it with required fields
var field_arr = [{name:'abc'},{email:'xyz'}];
var required = ['name', 'email' , 'tel'];
var inputKeys = field_arr.reduce(function(prev,next){
return prev.concat(Object.keys(next));
},[]);
document.write('<pre>inputKeys => ' +inputKeys+'</pre>');
var missingKeys = required.filter(function(key){
return inputKeys.indexOf(key) == -1;
});
document.write('<pre>missingKeys => ' +missingKeys+'</pre');
alert('You are missing '+missingKeys);
You want to :
turn your field_arr object into a key=>value type object
then loop on your required list to check that each item is a key in that object :
Code :
var arr = {};
for(var i=0; i<field_arr.length; i++){
var key = Object.keys(field_arr[i])[0];
arr[key] = field_arr[i][key];
}
// At this point you have a key => value type array in "arr"
var required_list = ["name", "email", "tel"];
for(var i=0; i<required_list.length; i++){
var item = required_list[i];
if(! item in arr) {
alert(item+" is missing");
}
}
If you want to use forEach instead of a for loop :
var arr = {};
field_arr.forEach(function(obj){
var key = Object.keys(obj)[0];
arr[key] = obj[key];
});
}
// At this point you have a key => value type array in "arr"
var required_list = ["name", "email", "tel"];
required_list.forEach(function(item){
if(! item in arr)
alert(item+" is missing");
});

Calling an array item into another array

I faced the following functions (or method I don't what is right name of the ):
function getRowArray($scope, object, i){
i = i + 1;
var item = {};
var data = [];
var id = -1;
if ($scope.selectedType !== undefined) {
id = $scope.selectedType.id;
}
var rating = getRating($scope, object, id);
item['name'] = $scope.objectInfo[object]['name'];
item['objectId'] = rating.objectId;
item['hideRating'] = parseInt($scope.objectInfo[object].hideControls) & 1;
item['addInfo'] = rating.addInfo;
item['rating'] = rating.value;
item['ratingId'] = rating.id;
for (var i in $scope.objectInfo[object].childs) {
if ($scope.objectInfo[object].childs[i] == object){
continue;
}
data.push(getRowArray($scope, $scope.objectInfo[object].childs[i], i));
}
item['data'] = data;
return item;
}
and
function getTypeRow($scope, oobject, otype){
var item = {};
var data = [];
var rating = getRating($scope, oobject.id, otype.id);
item['name'] = otype.name;
item['objectId'] = rating.objectId;
item['typeId'] = rating.typeId;
item['ratingId'] = rating.id;
item['addInfo'] = rating.addInfo;
item['rating'] = rating.value;
// item['hideRating'] = parseInt($scope.objectInfo[object].hideControls);
return item;
}
I want to use the hideRating item from the first one in the second, I tried and added the commented line but I got an error it says the object is undifined, is it wrong like that or am I missing something ? thanks in advance
object is undefined because it wasn't initialized; it's not specified in the parameter list for the function getTypeRow. The oobject in the parameter list should be corrected to object:
// Correct 'oobject' to 'object'
function getTypeRow($scope, object, otype){
var item = {};
var data = [];
// Correct 'oobject' to 'object'
var rating = getRating($scope, oobject.id, otype.id);
...
}

Get 2 values from JSON array nodejs

I want to get two values from my JSON array. It looks like that:
http://pastebin.com/tm5StsZ3
I need to get a ID and key from these arrays.
Please help me, thanks.
I am using newest node js.
ES6 syntax.
JSON.parse(data).map((item) => { item.id , item.key })
ES5
JSON.parse(data).map(function(item){ return {item.id , item.key }})
Loop through it like this:
var jsonData = JSON.parse(data);
for(var myobject in jsonData){
console.log("Id =" + myobject.id);
console.log("key = " + myobject.key);
}
or like this:
var jsonData = JSON.parse(data);
for(i = 0; i < jsonData.length; i++){
console.log("Id =" + jsonData[i].id);
console.log("key = " + jsonData[i].key);
}
var val1 = arr[0].id;
var k1 = arr[0].key;
var val2 = arr[1].id;
var k2 = arr[1].key;
To get the array lenght use arr.length
use map() function it will return te id and the key
var id = data.map(function(par){
return "id id :" +par.id+" key is: "+ par.key;
});
working see jsfiddle
Or you can is just a loop to access each key and id
for(i = 0; i < data.length; i++){
console.log("Id is :" + data[i].id+"key is : " + data[i].key);
}

Add a property to an object returned by a function?

I would like to know if there is a way to get all properties of 'myFields' assigned in a single statement ?
This works:
function fieldMap(namesString) {
var result = {};
var names = namesString.split(' ');
for (index in names) {
var name = names[index];
result[name] = name + '/text()';
}
return result;
}
var myFields = fieldMap('title rating author url');
myFields['cover']="#cover";
This doesn't work:
var myFields = fieldMap('title rating author url')['cover']='#cover';
If you want to change all properties of an object in a single statement, you have to write yourself a mapping method:
function fieldMap(namesString) { // Mike Lin's version
var result = {};
var names = namesString.split(' ');
for (var i=0; i<names.length; i++) {
var name = names[i];
result[name] = name + '/text()';
}
return result;
}
Object.prototype.map = function(callbackOrValue){
/* better create an object yourself and set its prototype instead! */
var res = {};
for(var x in this){
if(typeof this[x] === "function")
res[x] = this[x];
if(typeof callbackOrValue === "function")
res[x] = callbackOrValue.call(this[x]);
else
res[x] = callbackOrValue;
}
return res;
}
Then you can use
var myFields = fieldMap('title rating author url').map(function(){return '#cover'};
/* ... or ... */
var myFields = fieldMap('title rating author url').('#cover');
However, if you want to set myFields and change the value in the same step, try this:
var myFields;
(myFields = fieldMap('title rating author url'))['cover']='#cover';

Javascript | Objects, Arrays and functions

may be you can help me. How can I create global object and function that return object values by id?
Example:
var chat = {
data : {
friends: {}
}
}
....
/*
JSON DATA RETURNED:
{"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
*/
onSuccess: function(f){
chat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends.push(f.users[i])
}
}
How can I create a new function (It will return values by friend_id)?
get_data_by_id: function (what, friend_id) {
/*obj.what = getfrom_globalobject(chat.data.friends???)*/
}
Example of use:
var friend_name = get_data_by_id(name, 62);
var friend_username = get_data_by_id(username, 62);
var friend_avatar = get_data_by_id(thumb, 62);
Try:
get_data_by_id: function (what, friend_id) {
return chat.data.friends[friend_id][what];
}
... but use it like:
var friend_name = get_data_by_id('name', 62);
...and set up the mapping with:
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i];
}
You cannot .push() to an object. Objects are key => value mappings, so you need to use char.data.friends[somekey] = f.users[i];
If you really just want a list with numeric keys, make x5fastchat.data.friends an array: x5fastchat.data.friends = [];
However, since you want to be able to access the elements by friend_id, do the following:
onSuccess: function(f){
x5fastchat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i]
}
}
get_data_by_id: function (what, friend_id) {
obj[what] = chat.data.friends[friend_id][what];
}
Note the obj[what] instead of your original obj.what: When writing obj.what, what is handled like a string, so it's equal to obj['what'] - but since it's a function argument you want obj[what].
Take a look at the following code. You can simply copy paste it into an HTML file and open it. click "go" and you should see the result. let me know if I did not understand you correctly. :
<script>
myObj = { "field1" : { "key1a" : "value1a" }, "field2" : "value2" }
function go()
{
findField(myObj, ["field2"])
findField(myObj, ["field1","key1a"])
}
function findField( obj, fields)
{
var myVal = obj;
for ( var i in fields )
{
myVal = myVal[fields[i]]
}
alert("your value is [" + myVal + "]");
}
</script>
<button onclick="go()">Go</button>
I would recommend using the friend objects rather than getting them by id and name.
DATA = {"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
// simple data store definition
Store = {items:{}};
NewStore = function(items){
var store = Object.create(Store);
store.items = items || {};
return store
};
Store.put = function(id, item){this.items[id] = item;};
Store.get = function(id){ return this.items[id]; };
Store.remove = function(id){ delete this.items[id]; };
Store.clear = function(){ this.items = {}; };
// example
var chat = {
data : {
friends : NewStore()
}
}
// after data loaded
chat.data.friends.clear();
for( var i = 0; i < DATA.users.length; i += 1 ){
var user = DATA.users[i];
chat.data.friends.put( user.friend_id, user );
}
getFriend = function(id){ return chat.data.friends.get( id ); }
var friend = getFriend(66);
console.log(friend.name);
console.log(friend.username);
console.log(friend.thumb);

Categories